Zend Framework2 - 设置提交表单时的错误信息样式

1、方法一,在视图脚本中直接判断是否有error message,若有定义样式,应用不方便

// FORM ROW
    $html = '<div class="form-group">';

    // LABEL
    $html .= '<label class="form-label" for="' . $element->getAttribute('id') . '">' . $element->getLabel() . '</label>';

    // ELEMENT
    /*
     - Check if element has error messages
     - If it does, add my error-class to the element's existing one(s),
       to style the element differently on error
    */
    if (count($element->getMessages()) > 0) {
        $classAttribute = ($element->hasAttribute('class') ? $element->getAttribute('class') . ' ' : '');
        $classAttribute .= 'input-error';
        $element->setAttribute('class', $classAttribute);
    }
    $html .= $this->view->formElement($element);
    /*
     * Of course, you could decide/need to do things differently,
     * depending on the element's type

       switch ($element->getAttribute('type')) {
           case 'text':
           case 'email': {

               break;
           }
           default: {

           }
       }
     */
    // ERROR MESSAGES
    // Custom class (.form-validation-error) for the default html wrapper - <ul>
    $html .= $this->view->FormElementErrors($element, array('class' => 'form-validation-error'));

    $html .= '</div>'; # /.form-group
    $html .= '<div class="clearfix" style="height: 15px;"></div>';

    return $html . PHP_EOL;


2.方法二,(推荐)

The better solution would be to extend the Zend\Form\View\Helper\FormElementErrors by your own class and then register the view-helper formElementErrors to your class. So basically you'd have something like this:

namespace Mymodule\Form\Helper;  //位置随意,名称对应目录

use Zend\Form\View\Helper\FormElementErrors as OriginalFormElementErrors;

class FormElementErrors extends OriginalFormElementErrors  
{
    protected $messageCloseString     = '</li></ul>';
    protected $messageOpenFormat      = '<ul%s><li class="some-class">';
    protected $messageSeparatorString = '</li><li class="some-class">';
}

Last thing then would be to register the view helper with this new Class. For this you provide the following code inside your Modules Module.php

public function getViewHelperConfig()
{
    return array(
        'invokables' => array(
            'formelementerrors' => 'Mymodule\Form\Helper\FormElementErrors'
        ),
    );
}


3.方法三,直接加上样式,应用比较简单,适用错误元素数量较少的情况

//within the view
echo $this->formRow($form->get('Name'));

I called each element of the form individually:

    //within the view
    echo $this->formLabel($form->get('Name'));
    echo $this->formInput($form->get('Name'));   
    echo $this->formElementErrors($form->get("Name"), array('class' => "some_class", 'message' => "errormessage"));




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值