Force a field to not be required
Asked Answered
S

2

26

I am using Symfony2 and FOSUserBundle.

Just as detailed in the documentation, I have overridden and created a "name" property in the User entity.

I do all necessary and finally get that field to be shown in the form view.

The thing is: when I go form_widget(form.name) and the input html tag is generated, a required="required" property is generated within it. And that causes the engine to red the input when the field is not filled in.

How do I do to tell the Symfony2 not to make that field mandatory? I guess that it has to be here:

        parent::buildForm($builder, $options);

    // add your custom field
    $builder->add('name', 'text', array('label' => 'form.name'));
    $builder->remove('username');

or here:

    /**
 * @ORM\Column(type="string", length="255")
 *
 * @Assert\MinLength(limit="0", message="The name is too short.", groups={"Registration", "Profile"})
 * @Assert\MaxLength(limit="255", message="The name is too long.", groups={"Registration", "Profile"})
 */
private $name;
Seibel answered 8/8, 2012 at 15:58 Comment(0)
G
61
$builder->add('name', 'text', array('label' => 'form.name','required' => false));
Germany answered 8/8, 2012 at 16:14 Comment(2)
+1 - Maybe there is to add that this just stops the HTML5-validation on the form element. All asserts etc. from your entity are still turned on and must still be valid before the entity can be persisted.Evulsion
Is there a way to do it, via validation groups? I can't seem to make them effect the html5 required attributes, which makes validation groups near on useless for me.Semimonthly
N
0

Try to use:

use Symfony\Component\Validator\Constraints\NotNull;


$builder->add('name', 'text', array('label' => 'form.name',
'constraints' => new NotNull()));
Nyctalopia answered 27/11, 2019 at 9:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.