簡體   English   中英

ZF2-在表單上僅顯示一個錯誤

[英]ZF2 - Show just one error on forms

我似乎無法讓ZF2僅顯示一條錯誤消息,用於失敗的表單驗證消息。

例如,一個EmailAddress驗證器最多可以傳遞回7條消息,並且如果用戶輸入了錯誤,通常會顯示以下內容:

oli.meffff' is not a valid hostname for the email address
The input appears to be a DNS hostname but cannot match TLD against known list
The input appears to be a local network name but local network names are not allowed

如何覆蓋該錯誤以顯示一些更友好的信息,例如“請輸入有效的電子郵件地址”,而不是上面的詳細信息?

好的,設法為此提出了一個解決方案。 我沒有像上面的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的擴展,具有覆蓋此功能的render函數:

// We only want a single message
$messages = array(current($messages));

然后,使用在此處發布到我的問題中的解決方案將助手插入到我的應用程序中。

暫無
暫無

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

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