symfony 3 choice validation issue

768 views Asked by At

I have a choice field (drop-down) which I want to validate against a DB table.

Essentially, if the value is in the query's results, it's valid.

It's not so clear to me how the callback reported in the Symfony guide works :(

However, I have a validation.yml file:

User\UserBundle\Entity\Group:
    properties:
        role:
            - Choice:
                groups: [signUp]
                callback: [User\UserBundle\Entity\Group, getRoles]

The entity Group.php

class Group
{
    /** @var int */
    private $id;

    //...

    public static function GetRoles()
    {
        return ['admin', 'user'];
    }
}

This example works fine but my issue comes when I try to get those values from the group repository GroupRepository.php

class GroupRepository extends EntityRepository
{
    public function getRoles()
    {
        return $this->createQueryBuilder('r')
            ->getQuery()
            ->getResult();
    }
}

What am I supposed to do at this stage? Is the approach I used correct or should I call the Group Repository directly in the validation.yml? Or am I totally way off?

1

There are 1 answers

0
Marcel Pfeiffer On BEST ANSWER

As I understand it you are trying to get those options from the repository like:

...
callback: [User\UserBundle\Repository\GroupRepository, getRoles]

This won't work as the Repository needs to be initialized through the Doctrine ORM service.

I guess you have to create a custom Constraint class and ConstraintValidator where the later is configured as a service and gets the entity manager passed as argument.

See http://symfony.com/doc/current/validation/custom_constraint.html