【问题标题】:Zend MultiCheckbox: set maximum selectionZend MultiCheckbox:设置最大选择
【发布时间】:2011-11-07 16:24:18
【问题描述】:

我又来了一个简单的问题。

是否有现有的 zend 验证器来设置用户可以选择的框的最大值。 我希望他们选择不超过 3 个框。

我在网上搜索过,唯一发现的是在表单元素的 isValid 函数中设置了一个错误。但是后来我遇到了问题,每个选定的框都会显示错误。 (所以 4 次或更多次)或者也许有人知道如何处理这个问题?如果我只能显示一次此错误,我的问题也将得到解决。

感谢您的帮助。

【问题讨论】:

  • 也许将它们分组,为您自己快速编写的组添加一个验证器。然后用组而不是每个元素显示错误。

标签: php zend-framework zend-form zend-form-element zend-validate


【解决方案1】:

您可以使用我的验证器,它会检查值的数量。我完全出于相同的目的使用 - 验证多选中所选值的最大和最小数量:

<?php
class App_Validate_ValuesNumber extends Zend_Validate_Abstract
{
    const TOO_LESS = 'tooLess';
    const TOO_MUCH = 'tooMuch';

    protected $_type = null;
    protected $_val = null;

    /**
     * @var array
     */
    protected $_messageTemplates = array(
        self::TOO_LESS => "At least %num% values required",
        self::TOO_MUCH => "Not more then %num%  required",
    );

    /**
     * @var array
     */
    protected $_messageVariables = array(
        'num' => '_val'
    );
    /**
     * Constructor for the integer validator
     *
     * @param string $type Comparison type, that should be used
     *                     TOO_LESS means that value should be greater then items number
     *                     TOO_MUCH means opposite
     * @param int    $val  Value to compare items number with
     */
    public function __construct($type, $val)
    {
        $this->_type = $type;
        $this->_val = $val;
    }

    /**
     * Defined by Zend_Validate_Interface
     *
     * Returns true if and only if $value is a valid integer
     *
     * @param  string|integer $value
     * @return boolean
     */
    public function isValid($value)
    {
        // Value shoul dbe greated
        if ($this->_type == self::TOO_LESS) {
            if (count($value) < $this->_val) {
                $this->_error(self::TOO_LESS);
                return false;
            }
        }

        // Value should be less
        if ($this->_type == self::TOO_MUCH) {
            if (count($value) > $this->_val) {
                $this->_error(self::TOO_MUCH);
                return false;
            }
        }
        return true;
    }
}

【讨论】:

  • 自己编写验证器当然是另一个很好的解决方案!我做了一些更改,因为验证器在每个复选框上运行。所以 $value 总是只包含 1 个值。我使用 $context 参数来获取值。
  • $this-&gt;someFormElement-&gt;-&gt;addValidator(new App_Validate_ValuesNumber(App_Validate_ValuesNumber::TOO_LESS, 3)) 表示应选择不少于 3 个值
【解决方案2】:

我今天刚打过这个。这是一个zend bug。 http://framework.zend.com/issues/browse/ZF-11667。该问题的修复存在差异,但在 1.12 发布之前不会出现。我不想等待,所以我修补了我的 Zend_Form_Element。修复效果很好。在修复之前,我在 MultiChecks 上的错误消息针对每个选中的框重复了一次。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多