Php – Access custom error messages for InArray validator when using Zend_Form_Element_Select

PHPzend-formzend-framework

I'm using Zend Framework 1.62 (becuase we are deploying the finished product to a Red Hat instance, which doesn't have a hgih enough PHP version to support > ZF1.62).

When creating a Form using Zend Form, I add a select element, add some multi options.
I use the Zend Form as an in-object validation layer, passing an objects values through it and using the isValid method to determine if all the values fall within normal parameters.

Zend_Form_Element_Select works exactly as expected, showing invalid if any other value is input other than one of the multi select options I added.

The problem comes when I want to display the form at some point, I cant edit the error message created by the pre registered 'InArray' validator added automatically by ZF. I know I can disable this behaviour, but it works great apart from the error messages. I've tryed the following:

$this->getElement('country')->getValidator('InArray')->setMessage('The country is not in the approved lists of countries');

// Doesn't work at all.

$this->getElement('country')->setErrorMessage('The country is not in the approved lists of countries');

// Causes a conflict elswhere in the application and doesnt allow granular control of error messages.

Anyone have any ideas?

Ben

Best Answer

I usually set validators as per my example below:

$this->addElement('text', 'employee_email', array(
            'filters'    => array('StringTrim'),
            'validators' => array(                
                array('Db_NoRecordExists', false, array(
                    'employees',
                    'employee_email',
                    'messages' => array(Zend_Validate_Db_Abstract::ERROR_RECORD_FOUND => 'A user with email address %value% already exists')
                ))
            ),
            'label'     => 'Email address',
            'required'  => true,
            ));

The validators array in the element options can take a validator name (string) or an array.

When an array is passed, the first value is the name, and the third is an array of options for the validator. You can specify a key messages with custom messages for your element in this array of options.

Related Topic