简体   繁体   中英

Symfony2 How To Change The Form ID

I have a form field that I want to change the ID on when rendering in Twig. For some reason it is not adding the ID to the form field.

Here is how I am doing this in Twig:

 {{ form_widget(form.purchaseOrderLineItem, { 'value': value, 'id': 'new_id',  'attr': {'style': 'display:none'} }) }} 

Here is what it is outputting:

  <input class="form-control" type="text" value="203543" />

Why is it not creating the form field with the ID?

There is no sense to add an id attribute, because he hardcode in the template form_div_layout.html.twig . But you can override it like this:

{% form_theme form _self %}

{% block widget_attributes %}
    {% spaceless %}
        {% if attr.id is not defined %}id="{{ id }}"{% endif %} name="{{ full_name }}"{% if read_only %} readonly="readonly"{% endif %}{% if disabled %} disabled="disabled"{% endif %}{% if required %} required="required"{% endif %}{% if max_length %} maxlength="{{ max_length }}"{% endif %}{% if pattern %} pattern="{{ pattern }}"{% endif %}
        {% for attrname, attrvalue in attr %}{% if attrname in ['placeholder', 'title'] %}{{ attrname }}="{{ attrvalue|trans({}, translation_domain) }}" {% else %}{{ attrname }}="{{ attrvalue }}" {% endif %}{% endfor %}
    {% endspaceless %}
{% endblock widget_attributes %}

{% block body %}
    {{ form(form) }}
{% endblock %}

id必须位于attr部分:

{{ form_widget(form.purchaseOrderLineItem, { 'value': value,  'attr': {'style': 'display:none', 'id':'new_id'} }) }} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM