Karolis
Karolis

Reputation: 2618

What is the recommended way to remove input name prefixes in symfony form

Say I have a form named myform with an input field named myinput. By default, symfony will generate HTML widget like:

<input name="myform[myinput]" ... >

This doesn't work with my current javascripts and I need to get the following instead:

<input name="myinput" ...>

I've searched quite a bit and found 2 ways to achieve this:

It seems like the first method is not recommended, since it would limit the ability to customize form rendering using prefixed blocks.

The 2nd method was recommended here and here.

However both methods will change the name of the form to null and as a result symfony will generate the form like:

<form name="" ...>

This is probably because form_div_layout.html.twig looks like:

<form name="{{ name }}" ...

Which doesn't validate as HTML5.

According to this page, "this is not a bug".

I know I can override the form_start block in the template and remove the name altogether, but it seems that the form wasn't designed to be used with null names in general (hence no check for name length in the template).

So my question is: What is the recommended and HTML5 compatible way to remove input name prefixes for symfony forms?

Upvotes: 1

Views: 1543

Answers (2)

Karolis
Karolis

Reputation: 2618

It was a bug in form rendering. I've submitted a pull request to symfony repo which was accepted.

Until the change is released, a temporary solution would be to add this code to your form theme:

{# fix HTML5 validation of forms with null names #}
{% block form_start %}
    {% set name = name|default(block_prefixes.1) %}
    {{ parent() }}
{% endblock %}

Upvotes: 1

  • Regarding PHP, I think either option is OK.
  • Regarding Twig, I'd go for creating a custom form theme and, optionally, apply it to all forms on the site. I think that's the Symfony way of rendering a form according to your, specific, needs (nullable form name).

Upvotes: 0

Related Questions