Symfony form: disable "required" for a field from Twig

18.1k Views Asked by At

I'm trying to disable the frontend HTML5 validation for a filed in a form built in Symfony.

In Twig, i use this code:

{{ form_widget(form.email, {'attr': {'class': 'form-control input-lg','novalidate': 'novalidate}}) }}

but the field is still considered as required. What am I doing wrong?

2

There are 2 best solutions below

5
On BEST ANSWER

You can set that in your form type to disable the field validation.

->add('test', null, array(
    'required' => false
))

If you want to disable it for the whole field you can try something like this:

{{ form_start(form, { attr: {novalidate: 'novalidate'} }) }}
5
On

You can just do this in twig:

{{ form_start(form, { attr: {novalidate: 'novalidate'} }) }}

Or you can do this in your formtype class:

->add('name', 'text', ['required' => false])

EDIT:

In example below, only name field will trigger html5 validation.

Formclass

->add('name', 'text')
->add('middlename', 'text', ['required' => false])

Twig

{{ form_start(form) }}
    <p>NAME: {{ form_widget(form.name) }}</p>
    <p>MIDDLENAME: {{ form_widget(form.middlename) }}</p>

    <p><button name="button">Submit</button></p>
{{ form_end(form) }}