[英]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
之前执行formrow
, forminput
的输入都具有错误类,但是当我自行进行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.