How to set a CSS ID attribute to a Symfony2 form input

我们两清 提交于 2019-12-03 16:13:26

问题


This question is similar to another question. There the solution for setting the CSS class was to add it into the 3rd parameter of a call to FormBuilder::add():

->add('title', null, array('attr' => array('class'=>'span2')))

Unfortunately, this does not work for setting the CSS id. When I do

->add('title', null, array('attr' => array('id'=>'title-field')))

... this is ignored. The ID remains something like namespace_formtype_field.

How can I set the CSS ID, if at all?


回答1:


You can do it when you render your field in twig, if you set your id outside of the 'attributes' array like so:

{{ form_widget(form.field, { 'id': 'my_custom_id',  'attr': { 'class' : 'my_custom_class }} )}}



回答2:


At twig level, you can simply do this:

{{ form_widget(form. title, { 'id': 'title-field' }) }}

Tested on Symfony 2.3.4




回答3:


Since an HTML element cannot have multiple ID's, what you're trying to accomplish isn't possible because Symfony already uses ID's on form elements.

The way to solve this would be to change your JavaScript to use classes instead and using

->add('title', null, array(
    'attr' => array(
        'class'=>'title-field'
    )
))

The other way is to change the ID's your JavaScript uses to the Symfony ones.




回答4:


I am convinced now there is no easy answer. The closest seems to in fact change the markup by using form theming. Thank you Michi for pointing this way.



来源:https://stackoverflow.com/questions/17070763/how-to-set-a-css-id-attribute-to-a-symfony2-form-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!