johnkork
johnkork

Reputation: 664

Symfony2 choice field : empty value

I'm stumbling upon a really simple question and I can't find out what I'm doing wrong :

I have an entity Post which can have a type, in my class declaration :

/**
 * @ORM\Column(name="type", type="text", nullable=true)
 */
private $type;

Then I want a form to create Posts : In my PostType::buildForm() function :

$builder->add('type', 'choice', array(
        'empty_data' => null,
        'empty_value' => 'No type',
        'multiple' => false,
        'expanded' => true,
        'choices' => \MyBundle\Entity\Application\Post::getTypes(), /* returns array('TYPE1' => 'TYPE_1', 'TYPE2' => 'TYPE_2', ...) */
        'required' => true,))

The plan is to have a radio list with :

But it seems like if I choose the option 'No type', the form won't validate, without giving any explicit error. Same thing happens with 'required' => false, with 'placeholder' instead of 'empty_value', ...

Can you spot my mistake ? What am I doing wrong ?

Thanks :)

Upvotes: 0

Views: 3687

Answers (2)

johnkork
johnkork

Reputation: 664

My mistake didn't come from the Type or the Entity, it came from the twig widgets overloading.

I was not displaying the value="" if {{ value }} was empty.

Make sure value="" is inside your "None" input radio tag, and in your other input radio tags aswell, of course ! Hope it helps someone ;)

Upvotes: 3

Rooneyl
Rooneyl

Reputation: 7902

You can't have an empty value on a choice field type and have it required. You are saying it must exist but may be empty, a contradiction.

It will work if you drop the 'required' => true

Upvotes: 1

Related Questions