Benjamin Lucas
Benjamin Lucas

Reputation: 380

Symfony2 constraints entity validation yml

I've a many to many relation (user and account). In the user entity, I've private property groups (array collection).

When I try to validate this property (groups) with a simple "NotBlank", it's not work. So I try this below (collection and choice).

I read this http://symfony.com/fr/doc/2.3/reference/constraints/Choice.html and this http://symfony.com/fr/doc/2.3/reference/constraints/Collection.html but it doesn't work or I don't correctly use them.

Can anybody gives me some help ?

/* USER accounts property 

...

/**
 * @ORM\ManyToMany(targetEntity="Account", mappedBy="users", cascade={"persist", "remove"})
 */
 private $accounts;

...

Than the userType

...
->add('accounts', 'genemu_jqueryselect2_entity', array(
                    "class"         => "CMiNewsBundle:Account",
                    "property"      => "name",
                    "multiple"      => "true",
                    "query_builder" => function (EntityRepository $er) use ($user)
                    {
                          return $er->createQueryBuilder('acc')
                                    ->join('acc.users','u')
                                    ->where('u.id = :userID')
                                    ->setParameter('userID' , $user);
                    }
                    )
)
...

The validation.yml

CM\Bundle\iNewsBundle\Entity\User:
    properties:

        ...

        accounts:
            - NotBlank: ~

        ...

Upvotes: 0

Views: 680

Answers (1)

Bartłomiej Wach
Bartłomiej Wach

Reputation: 1986

"NotBlank" assert checks if the property === null || property === ''. Since your property is a collection, you probably initialise it as an ArrayCollection in your constructor so it will never be null.

For collections you should use the "Count" assert

http://symfony.com/doc/current/reference/constraints/Count.html

It forces you to set the "maximum" count as well as the minimum so you might want to create your own assert.

Upvotes: 2

Related Questions