Setting name attribute of symfony 2 form field

六眼飞鱼酱① 提交于 2019-12-19 07:37:06

问题


How to set name attribute of rendered field in symfony 2?

Expected output:

     <input type="text" name="test" value="test" />

Rendering the field this way

     {{ form_widget(form.test, { 'attr': {'name': 'test'} }) }}

definitely does not work.

Output is still

     <input type="text" name="form[test]" value="test" />.

Is there any way to set the name attribute or id attribute dynamically? Thank you.


回答1:


<input type="text" name="form[test]" value="test" />

already has test as name. Of course there is still the root form name called form in your case. Removing this is not really recommended, because when you read the request to populate form data you can identify the form by its form name.

Read [Form] Enable empty root form name https://github.com/symfony/symfony/pull/2936




回答2:


overriding Twig block this way:

{% block widget_attributes -%}
id="{{ id }}"
{%- if read_only %} readonly="readonly"{% endif -%}
{%- if disabled %} disabled="disabled"{% endif -%}
{%- if required %} required="required"{% endif -%}
{%- for attrname, attrvalue in attr -%}
    {{- " " -}}
    {%- if attrname in ['placeholder', 'title'] -%}
        {{- attrname }}="{{ attrvalue|trans({}, translation_domain) }}"
    {%- elseif attrvalue is sameas(true) -%}
        {{- attrname }}="{{ attrname }}"
    {%- elseif attrvalue is not sameas(false) -%}
        {{- attrname }}="{{ attrvalue }}"
    {%- endif -%}
{%- endfor -%}
name={{full_name}}
{%- endblock widget_attributes %}

The change is just moving name={{full_name}} from the first line to the last one, so when you add the name attr to the form builder add element, the name will be no longer ignored.



来源:https://stackoverflow.com/questions/12691021/setting-name-attribute-of-symfony-2-form-field

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