[英]Override form field templates in Symfony2
I want to override base Symfony2 form input field, to add my class, but it does not work. 我想覆盖基本的Symfony2表单输入字段,以添加我的类,但是它不起作用。 Here is my code AcmeDemoBundle:Form:fields.html.twig
这是我的代码AcmeDemoBundle:Form:fields.html.twig
{% extends 'form_div_layout.html.twig' %}
{% block form_widget_simple %}
{% set type = type|default('text') %}
<input type="{{ type }}" {{ block('widget_attributes') }} {% if value is not empty %}value="{{ value }}" {% endif %} class="testik_class"/>
{% endblock form_widget_simple %}
In config.yml
在config.yml
# Twig Configuration
twig:
debug: "%kernel.debug%"
strict_variables: "%kernel.debug%"
form_themes:
- 'AcmeDemoBundle:Form:fields.html.twig'
But it does not work. 但这行不通。 In my form class
attr still equal to custom_form
. 在我的表单class
attr仍然等于custom_form
。 What I am doing wrong? 我做错了什么? Maybe I overiding incorect block ? 也许我覆盖不正确的障碍? Can somebody help me? 有人可以帮我吗? Thanks! 谢谢!
Additionals: Here is my form type: 其他:这是我的表格类型:
/**
* {@inheritDoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('title', 'text', ['label' => 'form.title'])
->add('content', 'textarea', ['label' => 'form.content'])
;
}
Here is form template: 这是表单模板:
{{ form_widget(form) }}
Insteresting that when I try override textarea_widget
block or integer_widget
, all works fine. 令人惊讶的是,当我尝试覆盖textarea_widget
块或integer_widget
,一切正常。 Or when I try to add data-*
attr to simple_widget
it works fine too. 或者,当我尝试将data-*
attr添加到simple_widget
它也可以正常工作。 But class
not appends. 但是class
没有附加。
If you only want to override a class, you can simply do: 如果只想覆盖一个类,则可以简单地执行以下操作:
{{ form_widget(form, {'attr': {'class': 'testik_class'}}) }}
in your template, without using any specific form theme. 在模板中,而不使用任何特定的表单主题。 This solves your problem and makes your code even more readable. 这解决了您的问题,并使您的代码更具可读性。
Or even when you build your form in PHP: 甚至当您使用PHP构建表单时:
$builder->add('title', 'text', ['label' => 'form.title', 'attr' => array( 'class' => 'testik_class')])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.