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?
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.
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';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With