It appears there is a bit of a bug in Symfony2, although it may have been patched with the more recent versions.
If you have created a formtype and one of your inputs is an entity, you may wish to have the first element in the drop down list to be empty (null).
To do this, you just specify 'empty_value' as a parameter when adding the input to the builder:
$builder->add ( 'person', 'entity', array ( 'class' => 'Me\MyBundle\Entity\Person', 'empty_value' => 'Please choose a person' ) );
If you do this, then the first option will have a null value, and a label 'Please choose a person'.
This works great. However, the current symfony2 documentation says that this null option appears automatically if the input is NOT mandatory. In order to disable this first empty option, you have to turn off the empty_value parameter by doing this:
$builder->add ( 'person', 'entity', array ( 'class' => 'Me\MyBundle\Entity\Person', 'empty_value' => false ) );
But this doesn't work. If you do this, you will get an error message:
Notice: Undefined variable: emptyValue in /home/one45dev/workspace/platform/vendor/symfony/src/Symfony/Component/Form/Extension/Core/Type/ChoiceType.php line 85
In fact, if you want to disable the first empty option, you have to set empty_value to null , not false:
$builder->add ( 'person', 'entity', array ( 'class' => 'Me\MyBundle\Entity\Person', 'empty_value' => null ) );
Very nice Post. Thank You.
ReplyDeleteGreat post thanks
ReplyDeleteGreat explanation, thanks
ReplyDelete