Search code examples
symfonyrequiredformbuilder

Symfony 2.8 - FormBuilder : why field becomes required when I define its type?


I'm building a form like with two non mandatory fileds :

$form = $this->createFormBuilder($contact);
$form->add('name');
$form->add('subject', TextType::class);
$form->getForm();

After rendering the first field is not required (it's normal) but why the second is ?! What's wrong with this code ?

Thanks :)


Solution

  • required default value is defined in type class method configureOptions()

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'required' => true,
        ));
    }
    

    and in all parents for this type (parent is defined by getParent() method)
    first parent is Symfony\Component\Form\Extension\Core\Type\FormType and there required default value is defined as true, to it is strange that first input is not required.

    you can define required while adding new element $form->add('subject', TextType::class, array('required' => false));