好的,設法爲此提出了一個解決方案。我沒有像Sam上面提到的那樣爲所有驗證器失敗使用相同的字符串,而是重寫了InputFilter中元素的錯誤消息,然後使用自定義窗體錯誤視圖幫助器僅顯示第一條消息。
這裏是助手:
<?php
namespace Application\Form\View\Helper;
use Traversable;
use \Zend\Form\ElementInterface;
use \Zend\Form\Exception;
class FormElementSingleErrors extends \Zend\Form\View\Helper\FormElementErrors
{
/**
* Render validation errors for the provided $element
*
* @param ElementInterface $element
* @param array $attributes
* @throws Exception\DomainException
* @return string
*/
public function render(ElementInterface $element, array $attributes = array())
{
$messages = $element->getMessages();
if (empty($messages)) {
return '';
}
if (!is_array($messages) && !$messages instanceof Traversable) {
throw new Exception\DomainException(sprintf(
'%s expects that $element->getMessages() will return an array or Traversable; received "%s"',
__METHOD__,
(is_object($messages) ? get_class($messages) : gettype($messages))
));
}
// We only want a single message
$messages = array(current($messages));
// Prepare attributes for opening tag
$attributes = array_merge($this->attributes, $attributes);
$attributes = $this->createAttributesString($attributes);
if (!empty($attributes)) {
$attributes = ' ' . $attributes;
}
// Flatten message array
$escapeHtml = $this->getEscapeHtmlHelper();
$messagesToPrint = array();
array_walk_recursive($messages, function ($item) use (&$messagesToPrint, $escapeHtml) {
$messagesToPrint[] = $escapeHtml($item);
});
if (empty($messagesToPrint)) {
return '';
}
// Generate markup
$markup = sprintf($this->getMessageOpenFormat(), $attributes);
$markup .= implode($this->getMessageSeparatorString(), $messagesToPrint);
$markup .= $this->getMessageCloseString();
return $markup;
}
}
這只是FormElementErrors的延伸與覆蓋包括此渲染功能:
// We only want a single message
$messages = array(current($messages));
我然後使用該解決方案我插入助手到我的應用程序發佈到我的問題here。
確認'$ form-> get('email') - > setMessage('Wrong E-Mail dude!');'除此之外,你需要設置你不想看到的消息到'''' – Sam
謝謝山姆。視圖助手是否不會爲空白消息生成標記?我正在設計默認的'li'元素。我想我可以寫一個自定義的formElementErrors視圖幫手.. – MrNorm
嗯,是的,如果你去與第二個選項標記將生成。但是,如果你從你的控制器執行'setMessage()',只有你的自定義消息將顯示(iirc) – Sam