2
votes

I want to validate an email entity using @Assert\NotBlank and @Assert\Email, only if checkbox is checked ($updateEmailCheckBox). Because now those asserts are defined in annotation of email field and the validation occurs also when the checkbox is not checked.

Here's the snippet of my User enity:

 /**
 * Update email checkbox entity
 */
 private $updateEmailCheckBox;

 /**
 * @var string
 * @Assert\NotBlank(message="Email can't be empty")
 * @Assert\Email(message="Wrong email pattern")
 */
private $email;

/**
 * @Assert\Callback
 */
public function validate(ExecutionContextInterface $context)
{
    /**
     * If update email checkbox is checked
     */
    if ($this->getUpdateEmailCheckBox() == 1)
    {
        // how to validate here an email field for Assert\NotBlank and Assert\Email ?
    }
}

I can check whether checkbox is checked or not using callback, but I can't figure out how to enable NotBlank and Email validations, and in case of an constraint violation return corresponding errors.

1

1 Answers

3
votes

You can use validation groups.

 /**
 * @Assert\NotBlank(groups={"updateEmail"})
 * @Assert\Email(groups={"updateEmail"})
 */
private $email;

And when you want to validate your user in your controller or service, you validate agains this group (if checkbox is checked).

$errors = $validator->validate($user, null, array('Default', 'updateEmail'));

Default: Contains the constraints in the current class and all referenced classes that belong to no other group.

If you're using form then you should configure your form to use validation groups also. Something like this:

public function configureOptions(OptionsResolver $resolver)
{
   $resolver->setDefaults(array(
       'validation_groups' => function (FormInterface $form) {
           $data = $form->getData();


           if (/* checkbox is checked */) {
               return array('Default', 'updateEmail');
           }

           return array('Default');
    },
   ));
}