Search code examples
phpzend-frameworkvalidationzend-formzend-form-element

Messages not working on Zend_Form_Element_Text


In a form, I have the following element:

    $email = new Zend_Form_Element_Text('username');
            $email
                    ->setLabel($this->getView()->l('E-mail'))
                    ->setRequired(TRUE)
                    ->addValidator('EmailAddress')
                    ->addValidator('Db_NoRecordExists', true,
                            array(
                                'table' => 'pf_user',
                                'field' => 'email',
                                'messages' => array(
                                    'recordFound' => 'This username is already registered',
                                )
                    ))
                    ->setErrorMessages(array(
                        'emailAddressInvalidFormat' => 'You must enter a valid e-mail',
                        'isEmpty' => 'You must enter an e-mail',
                        'recordFound' => 'This e-mail has already registered in out database'
                    ));
$form->addElement($email)

the problem is that I always I get the same message "You must enter a valid e-mail" (the first one). Does anybody knows what is the mistake??


Solution

  • Actually, what you're doing is the following :

    1. You set the errors on the element
    2. Zend now thinks that the element did not validate correctly and that the first error is "You must enter a valid e-mail"
    3. When you display the form, since you set errors, Zend will find them and display the first one it finds. If you switch the order then you'll find that whichever error you put up top will be the error you get.

    The more correct way is to set the custom messages in the validator. When the validators are called to validate the element, if the validation fails, the validator will call the setErrorMessages on the element to set the custom errors you specify. Use this type of code below to set your custom messages.

    $element->addValidator( array( 'Db_NoRecordExists', true, array( 
    'messages' = array(
    Zend_Validate_Db_Abstract::ERROR_NO_RECORD_FOUND => 'Myy custom no error record',
    Zend_Validate_Db_Abstract::ERROR_RECORD_FOUND    => 'My custom record error'
    )
    ) ) );
    

    You'll find that usually there are consts in each validator class that specify one type of error. In this case, the consts are in the parent class of the DB_NoRecordExists class but usually you'll find them directly in the class near the top.