【问题标题】:zendfamework 2 form validation set attributes to an inputzendamework 2 表单验证集属性到输入
【发布时间】:2014-07-04 11:27:49
【问题描述】:

是否可以在使用输入过滤器验证表单时不仅发送错误消息,还将边框颜色更改为红色?

类似这样的:

$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'
                    )
                )
            )
        )
    ));

【问题讨论】:

标签: zend-framework2


【解决方案1】:

这样做的一种方法是创建您自己的视图助手来呈现表单元素,并在该字段有错误时添加错误类。

首先,您需要创建视图助手,如果表单元素有错误,则添加一个类。

视图助手:

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()
        );
    }

}

你需要添加到你的module.config.php

    'view_helpers' => array(
        'invokables'=> array(
            'formInput' => 'Application\View\Helper\FormInput',
        ),
    ),

【讨论】:

    猜你喜欢
    • 2013-12-17
    • 1970-01-01
    • 2017-09-14
    • 1970-01-01
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多