0

我的表单有多个元素以以下格式呈现:

<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')); ?>,输入被放入标签(我不想要)并且输入按预期获得错误类:

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

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

当我formrow之前这样做forminput时,两者中的输入都有错误类,但是当我forminput自己这样做时,它没有。

[编辑]

短期我已将formrow(没有回显)放在现有代码之上,现在我的输入字段显示错误类,但这感觉有点像黑客,我必须为我的应用程序中的每个元素都这样做已经设置成这样了。

4

1 回答 1

1

我创建了一个视图助手来将缺少的类添加到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();
    });
}
于 2017-01-18T10:26:04.903 回答