3

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 Answer 1

4

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');
    },
   ));
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! It seems to be that my approach was totally wrong :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.