Home » Php » php – Symfony form: disable "required" for a field from Twig

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

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&Answers:

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'} }) }}

Answer:

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) }}