1

As the title suggests, I have a choice field (radio html input) in my form which must have a selection before the user is allowed to proceed.

I have tried adding the validation into my validation.yml file in the bundle (throws an error saying that the field is not a valid entity field), and I have also tried the adding a validator directly in the form code, but received an Exception because the validator classes don't implement the FormValidatorInterface (code is below).

$builder->addValidator(new  CallbackValidator(function(FormInterface $form) {
     if(!$form['has_subalbums']->getData())
     {
         $form->addError(new FormError('Please indicate sub albums'));
     }
}));

What is the correct way to validate non-entity fields?

j0k
  • 22,600
  • 28
  • 79
  • 90
JamesHalsall
  • 13,224
  • 4
  • 41
  • 66
  • 1
    See the perfect answer here for Symfony 2.1: [Symfony 2 : Add a custom form element, not in an Entity][1] [1]: http://stackoverflow.com/q/10950203/354578 – Gregoire Aug 20 '12 at 15:52

2 Answers2

5

Try:

use Symfony\Component\Form as Form; [...]

 $builder->addValidator(new Form\CallbackValidator(function($form) {
 if(!$form['has_subalbums']->getData())
 {
     $form->addError(new Form\FormError('Please indicate sub albums'));
 }
 }));
webda2l
  • 6,686
  • 2
  • 26
  • 28
2

You can find an answer here:

Elnur Abdurrakhimov
  • 44,533
  • 10
  • 148
  • 133