12
votes

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?

1
Read the part of the manual page you posted where it says: Constraint Validators with Dependenciesgview
Hi thanks gview. I followed that part of the manual but there's incomplete detail on how to implement a validator constraint as a service.Acyra

1 Answers

5
votes
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';
}