簡體   English   中英

ZF2 FormInput在驗證失敗時顯示錯誤類

[英]ZF2 FormInput to show error class on validation fail

我的表單具有以以下格式呈現的多個元素:

<div class="form-group">
    <?php echo $this->formlabel($form->get('lastname')); ?>
    <?php echo $this->forminput($form->get('lastname')); ?>
    <?php echo $this->formElementErrors($form->get('lastname')); ?>
</div>

我這樣做是為了讓我可以將元素放在標簽旁邊而不是標簽里面:

<label for="lastname">Lastname</label><input .../>
<ul><li>error messages</li></ul>

我注意到的是,在驗證失敗時,輸入沒有得到input-error類。 當我將上面的代碼更改為<?php echo $this->formrow($form->get('lastname')); ?> <?php echo $this->formrow($form->get('lastname')); ?>輸入被放入標簽(我不想要),並且輸入得到預期的錯誤類:

<label>Lastname<input ... class="input-error"/></label>

如何通過$this->forminput將input-error類添加到元素中?

當我在formrow之前執行formrowforminput的輸入都具有錯誤類,但是當我自行進行forminput時,則沒有錯誤類。

[編輯]

短期來說,我已經將formrow (沒有回聲)放在了現有代碼之上,現在我的輸入字段顯示了錯誤類,但這聽起來有點像hack,對於應用程序中的每個元素,我都必須這樣做我已經這樣建立了。

我創建了一個視圖助手,將缺少的類添加到forminput

<?php
/**
 * Extend zend form view helper forminput to add error class to element on validation
 * fail
 * 
 * @package    RPK
 * @author     Richard Parnaby-King
 */
namespace RPK\Form\View\Helper;
use Zend\Form\View\Helper\FormInput as ZendFormInput;

class FormInput extends ZendFormInput
{
    protected $inputErrorClass = 'input-error';

    /**
     * Render a form <input> element from the provided $element
     *
     * @param  ElementInterface $element
     * @throws Exception\DomainException
     * @return string
     */
    public function render(\Zend\Form\ElementInterface $element)
    {
        $inputErrorClass = $this->inputErrorClass;

        // Following code block copied from \Zend\Form\View\Helper\FormRow
        // Does this element have errors ?
        if (count($element->getMessages()) > 0 && !empty($inputErrorClass)) {
            $classAttributes = ($element->hasAttribute('class') ? $element->getAttribute('class') . ' ' : '');
            $classAttributes = $classAttributes . $inputErrorClass;

            $element->setAttribute('class', $classAttributes);
        }
        return parent::render($element);
    }
}

然后,我告訴我的應用程序在Module.php文件中使用此視圖幫助器:

public function onBootstrap(MvcEvent $e) {
    $services = $e->getApplication()->getServiceManager();
    //add custom forminput viewhelper
    $services->get('ViewHelperManager')->setFactory('forminput', function (\Zend\View\HelperPluginManager $manager) {
        return new \RPK\Form\View\Helper\FormInput();
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM