I have got a simple smyfony2 form with one choices element. When I choose "kerosin" or "diesel" the form won't validate, what is correct. When I won't choose any of the three options and submit the form empty, $form->validate() will return true, but it shouldn't. Any ideas? Using the HTML5 required is not a solution for me.
This is my Form AbstractType:
public function buildForm(FormBuilderInterface $builder, array $options)
{
// Form erzeugen
$builder->add('treibstoff', 'choice', array(
'choices' => array(
'kerosin' => 'form.quiz1.kerosin',
'benzin' => 'form.quiz1.benzin',
'diesel' => 'form.quiz1.diesel',
),
'multiple' => false,
'expanded' => true,
'label' => ' '
))
->getForm();
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
// Validierung erzeugen
$collectionConstraint = new Collection(array(
'treibstoff' => array(
new Choice(array(
'choices' => array('benzin'),
'message' => 'form.quiz.falscheantwort',
'strict' => true
)
)
)
));
$resolver->setDefaults(array(
'validation_constraint' => $collectionConstraint
));
}
public function getName()
{
...
Validation works like this:
if($Request->getMethod() == "POST") {
$form->bind($Request);
if($form->isValid()) {
echo "valid";
Thanks in advance.
Edit:
I changed the setDefaultOptions like suggested and added NotBlank. That worked out for me:
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
// Validierung erzeugen
$collectionConstraint = new Collection(array(
'treibstoff' => array(
new Choice(array(
'choices' => array('benzin'),
'message' => 'form.quiz.falscheantwort',
'strict' => true,
)
),
new NotBlank()
)
));
$resolver->setDefaults(array(
'validation_constraint' => $collectionConstraint
));
}