How to pass in a parameter to a custom Zend validator?

3.4k Views Asked by At

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;
3

There are 3 best solutions below

3
On BEST ANSWER

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 your isValid() method in your validator should look something like this:

public function isValid($value, $context = null)
{
    $campaign_id = $context['campaign_id'];
    // Now build your query using $value - from the element to which this 
    // validator is attached - and the $campaign_id provided by the context.
    // And, of course, return true/false as required.
}
7
On

I think to make new Generic_ValidateUniqueAdGroupName($campaign_id) work you need to define a constructor for Generic_ValidateUniqueAdGroupName class and a variable called e.g. $_campaign_id. A draft is below:

class  Generic_ValidateUniqueAdGroupName extends Zend_Validate_Abstract {

   protected $_campaign_id;

   public function __construct($campaign_id) {
      $this->_campaign_id = $campaign_id;
   }

}

With this, you would access the id in your query as $this->_campaign_id.

0
On

You need to supply the $options argument:

Implementation in Zend_Form_Element:

public function addValidator($validator, $breakChainOnFailure = false, $options = array())

So, you'd do something like this:

$validator = new new Generic_ValidateUniqueAdGroupName();
$adgroup_name
    ->addValidator($validator, false, array('campaign_id' => 1));