简体   繁体   中英

Zend_Form decorators: Unable to view error messages (validation)

When we add decorators to the form elements in zend, the validation message doesn't shows why ?

Code Example :

$this->addElement('Text', 'Last_Name',array(
        //'decorators' => $this->elementDecoratorsTr,
        'label' => 'Last Name:',
        'required' => false,
        'filters' => array('StringTrim'),
            'validators' => array(array('validator' => 'StringLength','validator' => 'Alpha')) 
        ));

Here is Zend_Form_Element source code:

$decorators = $this->getDecorators();
if (empty($decorators)) {
    $this->addDecorator('ViewHelper')
        ->addDecorator('Errors')   // notice Errors decorator
        ->addDecorator('Description', array('tag' => 'p', 'class' => 'description'))
        ->addDecorator('HtmlTag', array('tag' => 'dd', 
                                        'id'  => $this->getName() . '-element'))
        ->addDecorator('Label', array('tag' => 'dt'));
}

If you set your own decorators then the default ones are not loaded.

In order to see validation messages you need to have an Errors decorator among the decorators you set.

Here is and example for setting decorators for error msg:

We have element in the :

$title = $this->createElement('text', 'title');
    $title->setRequired(true)
        ->setLabel('Title:')
        ->setDecorators(FormDecorators::$simpleElementDecorators)
        ->setAttrib('maxlength', $validationConfig->form->title->maxlength)
        ->addValidator('stringLength', false, array($validationConfig->form->title->minlength,
                $validationConfig->form->title->maxlength,
                'encoding' => 'UTF-8',
                'messages' => array(
                    Zend_Validate_StringLength::INVALID =>
                    'Title must be between %min% and %max% characters',
                    Zend_Validate_StringLength::TOO_LONG =>
                    'Title cannot contain more than %max% characters',
                    Zend_Validate_StringLength::TOO_SHORT =>
                    'Title must contain more than %min% characters')));                     
    $this->addElement($title);

and this is class with form decorators, you can do a lot of them there:

 class FormDecorators {
    public static $simpleElementDecorators = array(
        array('ViewHelper'),
        array('Label', array('tag' => 'span', 'escape' => false, 'requiredPrefix' => '<span class="required">* </span>')),
        array('Description', array('tag' => 'div', 'class' => 'desc-item')),
        array('Errors', array('class' => 'errors')),
        array('HtmlTag', array('tag' => 'div', 'class' => 'form-item'))
    );
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM