I am trying to write a validator in Zend framework.
The validator queries the database to check if a particular record exists, this query uses a where clause. The value for the where clause is specified by another field on the form, so how do I pass this value into the validator?
This is how I add my validator:
$adgroup_name->addValidator(new Generic_ValidateUniqueAdGroupName() ); break;
Within my validator I have:
// Query which gets an array of existing ad group names in db
$q = Doctrine_Query::create()
->select('a.name')
->from('AdGroup a')
->where('a.name = ?', $value)
->andWhere('a.campaign_id = ?', $campaign_id);
$adgroup_names_result = $q->fetchOne(array(), Doctrine::HYDRATE_ARRAY);
How do I pass in $campaign_id? I've tried the following and it doesn't work:
$adgroup_name->addValidator(new Generic_ValidateUniqueAdGroupName($campaign_id) ); break;
The principle is the same as used in "confirm password" validators. You need the value of another element in the form in the field when the form is submitted. That's why attempting to instantiate the validator with the campaign_id is not working: the value of
$campaign_id
is not yet set.When an element calls
isValid()
on its validators, it passes a second parameter called$context
that is filled with an array of submitted form values. So yourisValid()
method in your validator should look something like this: