Valentin Maior
Valentin Maior

Reputation: 31

Symfony 2 Entity Validation Callback not being called

Could someone help me figure out why my Callback validation method is not being called.

Basically what I need to do is a custom validation with following logic: - in the form I have 5 fields that if all empty, the form should be valid, - however if any of the is not empty all of them need to not be empty (they are used to build a real address on a user profile)

I have followed the doc from: http://symfony.com/doc/2.3/reference/constraints/Callback.html

I have the following code:

/**
 * User
 *
 * @ORM\Table(name="user")
 * @ORM\Entity(repositoryClass="UserRepository");
 * @UniqueEntity("email")
 * @ORM\HasLifecycleCallbacks
 * @Assert\Callback(methods={"isAddressValid"})
 */
class User extends WebserviceUser implements UserInterface, EquatableInterface
{
...

    public function isAddressValid(ExecutionContextInterface $context)
    {
        //die("I GOT HERE");
        $context->addViolationAt('sna4', 'Frikin validation'!', array(), null);
    }
}

The property sna4 is found in the class being extended.

Thank you in advance.

Upvotes: 2

Views: 1882

Answers (1)

Matteo
Matteo

Reputation: 39390

The callback annotation require (if any is defined) the validation group associated.

As Example, an entity used in different form context with a validation custom for a specific form:

The Entity Class:

/**
 *
 * @Assert\Callback(methods={"validateCommunicationEmail"}, groups={"userProfile"})
 * @Assert\Callback(methods={"validatePreference"}, groups={"userPreference"})
 */
class AcmePreferences
{

    ....

        public function validateCommunicationEmail(ExecutionContextInterface $context)
    {
        if ($this->getIsCommunicationsEnabled() && ! $this->getAdministrativeCommunicationEmail())
        {
            $context->addViolationAt('isCommunicationsEnabled','error.no_administrative_email_selected');
        }

    }

}

The Form Type:

class AcmePreferencesType extends AbstractType
{

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class'=> 'Acme\DemoBundle\Entity\AcmePreferences',
            'validation_groups' => array('userProfile')
        ));
    }

Upvotes: 4

Related Questions