Carlos
Carlos

Reputation: 352

symfony 3.1 validation in entity getters

After a long search without a clear solution I need your advice:

I'm trying to do an example of this http://symfony.com/doc/current/validation.html#getters but I don't understand how to do it.

I understated that I have to have a method in the entity that does the validation, isPasswordLegal() in the example. But when is it called?.

Is this documentation saying that I can make an annotation like:

@Assert\isPasswordLegal()

or

@Assert\isTrue(isPasswordLegal)

in the password attribute?.

I also read this http://symfony.com/doc/current/reference/constraints/IsTrue.html but, like in the above mentioned link, the examples are the same without giving me a clue.

Thanks in advance.

Upvotes: 2

Views: 736

Answers (1)

galeaspablo
galeaspablo

Reputation: 885

Neither. Let's have a look at the example.

use Symfony\Component\Validator\Constraints as Assert;

/**
 * @Assert\IsTrue(message = "The password must be valid")
 */
public function isPasswordLegal()
{
    // ... return true or false
}

The @Assert\IsTrue() statement is not referring to another method in the class. The statement is referring to the method directly under the annotation.

In this case, function isPasswordLegal is directly under the annotation, so Assert\IsTrue() will validate that isPasswordLegal returns true. If it doesn't return true an error will be triggered.

Let's use this to complete the example.

use Symfony\Component\Validator\Constraints as Assert;

/**
 * @Assert\IsTrue(message = "The password must be valid!")
 */
public function isPasswordLegal()
{
    $password = $this->password;
    if($password !== "invalidPassword" && $password !== "anotherInvalidPassword"){
         return true;
    }
    else{
         return false;
    }
}

Edit: Answering a request for clarification in the comments:

An Assert annotation applies to the method underneath it. The method can validate anything you want. It is up to that method to check the password. The name of the method is irrelevant, it is just convention.

This validation will occur when you flush the entity, or when the associated form is validated.

Upvotes: 2

Related Questions