Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 validation value inside a form event listener?

I have the following snippet of code in a Symfony2 form:

$builder->add('AccountID');

$builder->get('AccountID')->addEventListener(
    FormEvents::POST_SUBMIT,
    function (FormEvent $Event) {
        //Do something but only if AccountID passed validation
    }
);

Right now POST_SUBMIT gets triggered whether it passes validation or not.

How can I tell if the field was properly validated inside the event listener?

I'd rather not have an if to check for the same validation I specified inside the validation.yml on the field.

Is this possible?

like image 669
Tek Avatar asked Apr 02 '15 20:04

Tek


2 Answers

in symfony 4 i do like this for validating form input base on another form element :

    ->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
                   $cardData=$event->getData();
                   $form=$event->getForm();

                    if(Your Valdiation Condition){

                        }
                        else{
                      $form->addError(new FormError("form error message"));
                        }
  });
like image 32
ghazaleh javaheri Avatar answered Nov 15 '22 05:11

ghazaleh javaheri


How about using $event->getForm()->isValid()?

This should be reliable if your event listener gets called after the validation step took place.

Note that the validation step is to be found within a form subscriber itself and is listening for POST_SUBMIT - same event you are trying to attach to.

For reference, check Symfony\Component\Form\Extension\Validator\EventListener\ValidationListener.

like image 99
Nikola Petkanski Avatar answered Nov 15 '22 05:11

Nikola Petkanski