Question

Is it possible to do while validate a form with an input filter to not just send an error message but also set the border colour change to red?

something like this:

$this->add(array(
        'name' => 'test',
        'required' => true,
        'attributes' => array(
                'style' => 'border-color:red'
        ),
        'validators' => array(
            array(
                'name' => 'NotEmpty',
                'options' => array(
                    'messages' => array(
                        \Zend\Validator\NotEmpty::IS_EMPTY => 'Please fill me out'
                    )
                )
            )
        )
    ));
Was it helpful?

Solution

One way of doing this would be to create your own view helper to render a form element and in that add error classes if the field has errors.

To start you need to create your view helper and if the form element has errors, then you add a class.

The view helper:

namespace Application\View\Helper;
use Zend\Form\View\Helper\FormInput as ZendFormInput;

use Zend\Form\ElementInterface;
use Zend\Form\Exception;

class FormInput extends ZendFormInput
{


    /**
     * Render a form <input> element from the provided $element    
     *
     * @param  ElementInterface $element
     * @throws Exception\DomainException
     * @return string
     */
    public function render(ElementInterface $element)
    {
        $name = $element->getName();
        if ($name === null || $name === '') {
            throw new Exception\DomainException(sprintf(
                '%s requires that the element has an assigned name; none discovered',
                __METHOD__
            ));
        }

        $attributes          = $element->getAttributes();
        $attributes['name']  = $name;
        $attributes['type']  = $this->getType($element);
        $attributes['value'] = $element->getValue();

        return sprintf(
            '<input %s class="form-control '.(count($element->getMessages()) > 0 ? 'error-class' : '').'" %s',
            $this->createAttributesString($attributes),
            $this->getInlineClosingBracket()
        );
    }

}

And to your module.config.php you will need to add

    'view_helpers' => array(
        'invokables'=> array(
            'formInput' => 'Application\View\Helper\FormInput',
        ),
    ),
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top