ZF2 FormInput 在验证失败时显示错误 class

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 class。当我将上面的代码更改为 <?php echo $this->formrow($form->get('lastname')); ?> 时,输入被放入标签(我不想要)并且输入如预期的那样得到错误 class:

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

如何通过 $this->forminput 将输入错误 class 放入元素中?

当我在 forminput 之前执行 formrow 时,两者的输入都有错误 class,但是当我单独执行 forminput 时,它没有。

[编辑]

短期内,我已将 formrow(没有回显)放在现有代码之上,现在我的输入字段显示错误 class,但这感觉有点像 hack,并且我必须为我的应用程序中的每个元素执行此操作,我已经像这样设置了。

我创建了一个视图助手来将缺失的 class 添加到 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();
    });
}