Highly Opinionated Thoughts on Programming

by Elnur Abdurrakhimov


Symfony: Disabling HTML5 Form Validation Globally

May 21, 2014


If for some reason you want to disable HTML5 form validation globally by changing something in one place only, here’s one way you could do it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
namespace Acme\Form\Extension;

use JMS\DiExtraBundle\Annotation\Service;
use JMS\DiExtraBundle\Annotation\Tag;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;

/**
 * @Service
 * @Tag(name="form.type_extension", attributes={"alias":"form"})
 */
class NoValidateExtension extends AbstractTypeExtension
{
    /**
     * {@inheritdoc}
     */
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $view->vars['attr'] = array_merge($view->vars['attr'], [
            'novalidate' => 'novalidate',
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function getExtendedType()
    {
        return 'form';
    }
}

Another way would be to add a custom form theme and override the form_start block, but using an extension feels like a better way to me.



© Elnur Abdurrakhimov