In Zf2, how to add a error css class on validation

2019-07-15 04:56发布

问题:

I want to add red border around Input Text Box when ZF2 Validation failed. I am thinking if ZF2 provide way to add/set css class in case of validation failure. It is better if it is possible using only Zend Validation/Form API. I am not considering client side (javascript/jQuery) solutions.

UPDATE :

I am using Form Row element like that

<div class="row">
    <div><?php echo $this->formLabel($form->get('first_name')); ?></div>
    <div><?php echo $this->formElement($form->get('first_name')); ?></div>
    <div><?php echo $this->formElementErrors($form->get('first_name'), array('class' => "field-validation-error")); ?></div>
</div>

回答1:

You can use FormRow view helper, which will render non-valid elements with CSS class ("input-error" by default).

Usage is very simple, in your template:

echo $this->formRow($element);

or if you want custom class:

echo $this->formRow()->setInputErrorClass('my-error-class')->render($element);


回答2:

If you wish to add specific 'error' classes to the input will need to modify the related Zend\Form\View\Helper\Form* classes as these are what introspect the Zend\Form\ElementInterface objects and render the required HTML.

For example:

// \MyModule\Form\View\Helper\MyCustomFormElement.php
class MyCustomFormElement extends \Zend\Form\View\Helper\FormElement
{

    public function render(Element $element)
    {
        $errors = $element->getMessages();

        if (! empty($errors)) {

            $classes = $element->getAttribute('class');

            if (null === $classes) $classes = array();
            if (! is_array($classes)) $classes = explode(' ', $classes);

            $classes = array_unique(array_merge($classes, array('my-error-class')));

            $element->setAttribute('class', implode(' ', $classes));
        }

        return parent::render($element);
    }

}

Then just replace the default form element helper by registering a invokable with the same name.

// Module.php
public function getViewHelperConfig()
{
    return array(
        'invokables' => array(
            'form_element' => 'MyModule\Form\View\Helper\MyCustomFormElement',
        ),
    );
}