Zend_Validate_Db_RecordExists against 2 fields

To do this you would have to extend the Zend_Validate_Db_RecordExists class.

It doesn't currently know how to check for the existence of more than one field.

You could just use two different validator instances to check the two fields separately. This is the only work around that I can see right now besides extending it.

If you choose to extend it then you'll have to find some way of passing in all the fields to the constructor ( array seems like a good choice ), and then you'll have to dig into the method that creates the sql query. In this method you'll have to loop over the array of fields that were passed in to the constructor.


You should look into using the exclude parameter. Something like this should do what you want:

$validator = new Zend_Validate_Db_RecordExists(
array(
        'table'   => $this->_name,
        'field'   => 'id_sector',
        'exclude' => array(
            'field' => 'day_of_week',
            'value' => $fields_values['day_of_week']
        )
);

The exclude field will effectively add to the automatically generated WHERE part to create something equivalent to this:

WHERE `id_sector` = $fields_values['id_sector'] AND `day_of_week` = $fields_values['day_of_week']

Its kind of a hack in that we're using it for the opposite of what it was intended, but its working for me similar to this (I'm using it with Db_NoRecordExists).

Source: Zend_Validate_Db_NoRecordExists example


Sorry for the late reply.

The best option that worked for me is this:

//  create an instance of the Zend_Validate_Db_RecordExists class
//  pass in the database table name and the first field (as usual)...
$validator = new Zend_Validate_Db_RecordExists(array(
    'table' => 'tablename',
    'field' => 'first_field'
));

// reset the where clause used by Zend_Validate_Db_RecordExists
$validator->getSelect()->reset('where');

// set again the first field and the second field. 
// :value is a named parameter that will be substituted 
// by the value passed to the isValid method
$validator->getSelect()->where('first_field = ?', $first_field);
$validator->getSelect()->where('second_field = :value', $second_field);

// add your new record exist based on 2 fields validator to your element.
$element = new Zend_Form_Element_Text('element');
$element->addValidator($validator);

// add the validated element to the form.
$form->addElement($element);

I hope that will help someone :)

Although, I would strongly recommend a neater solution which would be to extend the Zend_Validate_Db_RecordExists class with the above code.

Enjoy!! Rosario