Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Constraint Validator with Database Connection Dependency Symfony2

Tags:

symfony

I'm adding a custom validation query to a Symfony2 project.

The docs lack a complete example, and I'm not sure how to actually inject the database connection into the Validator Class. I've created the service in my config, added the validatedBy alias method in my Constraint class, and set up this in my Validator Class:

use Doctrine\DBAL\Connection;

class ZipDatabaseValidator extends ConstraintValidator
{

    /**
     *
     * @var Connection
     */
    private $connection;

   public function __construct(Connection $dbalConnection)  {

        $this->connection = $dbalConnection;
    }

    public function validate($zipcode, Constraint $constraint)
    {

        $sql = 'SELECT * FROM zip_table WHERE zip_code = ?';
        $stmt = $this->connection->prepare($sql); 
         ...

Here's my service config:

validator.node.zip_in_database:
        class: Acme\Bundle\Validator\Constraints\ZipDatabaseValidator
        arguments: [@database_connection]
        tags:
            - { name: validator.constraint_validator, alias: zip_in_database }

I keep getting errors, in this case:

Catchable Fatal Error: Argument 1 passed to Acme\Bundle\Validator\Constraints\ZipDatabaseValidator::__construct() must be an instance of Doctrine\DBAL\Connection, none given,

How the heck to I set this up as a service or otherwise inject the database connection?

like image 522
Acyra Avatar asked Jan 17 '13 02:01

Acyra


1 Answers

validator.node.zip_in_database:
    class: Acme\Bundle\Validator\Constraint\ZipDatabaseValidator
    arguments: [@database_connection]
    tags:
        - { name: validator.constraint_validator, alias: zip_in_database }

You must pass doctrine as an argument to your Service.

Edit

Make sure the alias is the same as the validatedBy method returns!
in your case:

//Acme\Bundle\Validator\Constraint\ZipDatabase class
public function validatedBy()
{
    return 'zip_in_database';
}
like image 173
Gintro Avatar answered Sep 18 '22 18:09

Gintro