Model validation Symfony2

I have read how to validate forms in server side with sf2. The solution is by using the Constraints in the Entity as annotations, validation.yml or inside the EntityType (Form).

Everything is fine, however, all of these validations work just with the form. But when you instance a new object and try to persist, validation doesn't work.

I will give you an example.

Imagine I have a user entity:

/**
 * @ORM\Entity
 * @ORM\Table(name="sf_user")
 */
class User{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string
     * @ORM\Column( name="username", type="string", length=50, unique=true )
     */
    protected $username;

    /**
     * @var string
     * @ORM\Column( name="email", type="string", length=100, unique=true )
     */
    protected $email;

    public static function loadValidatorMetadata(\Symfony\Component\Validator\Mapping\ClassMetadata $metadata)
    {
        $metadata->addPropertyConstraint('username', new \Symfony\Component\Validator\Constraints\NotBlank());

        $metadata->addPropertyConstraint('email', new \Symfony\Component\Validator\Constraints\NotNull());
    } 
}

Then, in some controller I try to save my form with:

$this->form = $this->create(new UserType());
$this->form->setData(new User());
$this->form->bind($this->request);

if( $this->form->isValid())
{
    //Persist with entity manager
}

Everything works perfectly because I have an association between my Entity and my form. But what happen if i need to instance an object without a form?. I should do something like this:

$user = new User();
$user->setUsername("username");
//Persist with entity manager

If I do that, entity is not validated and DB throws an error because the field "email" is required.

Should I always associate my entity with the form to validate? If that is the case, I don't agree at all because if I am working with web services, I don't wanna create a form just to validate on the server side.

So, how could I do this validation?. Thanks for your help.

Answers


You can use the validation service

$validator = $this->get('validator');
$validator->validate($user);

see the docs about this.


By the way there is a cleaner way to specify validation in you entity.

use Symfony\Component\Validator\Constraints as Assert;

class User{

/**
 * @Assert\NotNull
 */
protected $username;

/**
 * @Assert\NotBlank
 * @Assert\Email
 */
protected $email;

Need Your Help

How to execute tests on the argument that a controller passes to the view in Play Framework

scala playframework-2.0

In our play application every controller function fetches data from the database (or some other way) and passes these values to the result