4

我有一个带有许多选项的 Multiselect Zend Form 元素。我必须验证所选选项的数量(至少选择 N 个选项,最多选择 M 个选项)。我希望像常规 Zend Validate 错误消息一样以表单打印错误消息。

做到这一点的最简单(也是最简单)的方法是什么?

常规验证器无法做到这一点,因为每个选定的值都是单独验证的。

我试图覆盖表单的 isValid 方法并在那里添加逻辑(如果数字超出允许范围,则返回 false 并添加错误消息),但这会导致错误消息被打印多次(对于每个选定的值)。我觉得试图解决这个问题会导致代码非常糟糕。

感谢帮助

4

2 回答 2

1

不知道这对你来说是否太hacky。

$element = new Zend_Form_Element_Multiselect('CheckThis');
$options = array(
    1 => 'Option One',
    2 => 'Option Two',
    3 => 'Option Three',
    4 => 'Option Four',
    5 => 'Option Five',
    6 => 'Option Six',
    7 => 'Option Seven',
    8 => 'Option Eight',
);
$element->addMultiOptions($options);
$betweenOptions   = array('min' => 2, 'max' => 4);
$betweenValidator = new Zend_Validate_Between($betweenOptions);
$betweenValidator->setMessage("The number of submitted values '%value%' is not between '%min%' and '%max%', inclusively",'notBetween');
if ( true === $this->getRequest()->isPost() ) {
    if ( true === $betweenValidator->isValid(count($_POST['CheckThis'])) ) {
        $form->isValid($_POST);
    } else {
        $messages = $betweenValidator->getMessages();
        $element->addError($messages['notBetween']);
        $form->setDefaults($_POST);                
    }
}

更新
注意避免重复的错误消息。
如果您不能调用isValid表单或元素;就像在我的示例中,我只添加错误消息并设置默认值。问题是isValid($value)它将调用_getErrorMessages()并且该方法根据值检查错误消息。

如果您无法避免调用isValid我将扩展 Multiselect 元素并getErrorMessages()用我的一个逻辑覆盖该 _ 方法。您可以Zend/Form/Element.php在底部的类中找到该方法。

于 2011-09-12T22:56:08.403 回答
0

我决定创建我的自定义 Errors 元素装饰器,它会丢弃非唯一的错误消息:

<?php
class Element_Decorator_Errors extends Zend_Form_Decorator_Abstract
{
    /**
     * Render errors
     * 
     * @param  string $content 
     * @return string
     */
    public function render($content)
    {
        $element = $this->getElement();
        $view    = $element->getView();
        if (null === $view) {
            return $content;
        }

        // The array_unique is the only difference in comparison to the default Error decorator   
        $errors = array_unique($element->getMessages());
        if (empty($errors)) {
            return $content;
        }

        $separator = $this->getSeparator();
        $placement = $this->getPlacement();
        $errors    = $view->formErrors($errors, $this->getOptions()); 

        switch ($placement) {
            case self::APPEND:
                return $content . $separator . $errors;
            case self::PREPEND:
                return $errors . $separator . $content;
        }
    }
}
?>
于 2011-09-14T14:01:08.817 回答