开发者

Zend validate multi-select value

开发者 https://www.devze.com 2023-03-24 06:46 出处:网络
There is a multiselect element in form. It\'s needed to validate how many items are selected in it (min and max count).

There is a multiselect element in form. It's needed to validate how many items are selected in it (min and max count).

The trouble is that when the element can have multiple values, then each value is validated separately.

I tried to set isArray to false to validate the value with my custom validator ArraySize, but new problem appeared: the whole array-value is passed to InArray validator and the validation fails. So I had to turn it off by setting registerInArrayValidator to false.

Now I can validate the value for n开发者_如何学Pythonumber of selected values but can not validate for their correspondence to provided options.

Is there a way to solve the problem without creating one more custom validator?


Note: I have assume this is Zend 1.

The only way I could see to do this was to extend Multiselect and use a custom isValid. This way you can see the full array of values and not just one value at a time.

Below is my custom Multiselect class

<?php
/**
 * My_MinMaxMultiselect
 */
class My_MinMaxMultiselect extends Zend_Form_Element_Multiselect
{
    /**
     * Validate element contains the correct number of
     * selected items. Check value against minValue/maxValue
     *
     * @param mixed $value
     * @param mixed $context
     * @return boolean
     */
    public function isValid($value, $context = null)
    {
        // Call Parent first to cause chain and setValue
        $parentValid = parent::isValid($value, $context);

        $valid = true;

        if ((('' === $value) || (null === $value))
            && !$this->isRequired()
            && $this->getAllowEmpty()
        ) {
            return $valid;
        }

        // Get All Values
        $minValue = $this->getMinValue();
        $maxValue = $this->getMaxValue();

        $count = 0;
        if (is_array($value)) {
            $count = count($value);
        }

        if ($minValue && $count < $minValue) {
            $valid = false;
            $this->addError('The number of selected items must be greater than or equal to ' . $minValue);
        }

        if ($maxValue && $count > $maxValue) {
            $valid = false;
            $this->addError('The number of selected items must be less than or equal to ' . $maxValue);
        }

        return ($parentValid && $valid);
    }

    /**
     * Get the Minimum number of selected values
     *
     * @access public
     * @return int
     */
    public function getMinValue()
    {
        return $this->getAttrib('min_value');
    }

    /**
     * Get the Maximum number of selected values
     *
     * @access public
     * @return int
     */
    public function getMaxValue()
    {
        return $this->getAttrib('max_value');
    }

    /**
     * Set the Minimum number of selected Values
     *
     * @param int $minValue
     * @return $this
     * @throws Bad_Exception
     * @throws Zend_Form_Exception
     */
    public function setMinValue($minValue)
    {
        if (is_int($minValue)) {
            if ($minValue > 0) {
                $this->setAttrib('min_value', $minValue);
            }

            return $this;
        } else {
            throw new Bad_Exception ('Invalid value supplied to setMinValue');
        }
    }

    /**
     * Set the Maximum number of selected values
     *
     * @param int $maxValue
     * @return $this
     * @throws Bad_Exception
     * @throws Zend_Form_Exception
     */
    public function setMaxValue($maxValue)
    {
        if (is_int($maxValue)) {
            if ($maxValue > 0) {
                $this->setAttrib('max_value', $maxValue);
            }

            return $this;
        } else {
            throw new Bad_Exception ('Invalid value supplied to setMaxValue');
        }
    }

    /**
     * Retrieve error messages and perform translation and value substitution.
     * Overridden to avoid errors from above being output once per value
     *
     * @return array
     */
    protected function _getErrorMessages()
    {
        $translator = $this->getTranslator();
        $messages = $this->getErrorMessages();
        $value = $this->getValue();
        foreach ($messages as $key => $message) {
            if (null !== $translator) {
                $message = $translator->translate($message);
            }
            if (($this->isArray() || is_array($value))
                && !empty($value)
            ) {
                $aggregateMessages = array();
                foreach ($value as $val) {
                    $aggregateMessages[] = str_replace('%value%', $val, $message);
                }
                // Add additional array unique to avoid the same error for all values
                $messages[$key] = implode($this->getErrorMessageSeparator(), array_unique($aggregateMessages));
            } else {
                $messages[$key] = str_replace('%value%', $value, $message);
            }
        }

        return $messages;
    }
}

To use this in the form where the User must select exactly 3 options:

    $favouriteSports = new MinMaxMultiselect('favourite_sports');
    $favouriteSports
        ->addMultiOptions(array(
            'Football',
            'Cricket',
            'Golf',
            'Squash',
            'Rugby'
        ))
        ->setRequired()
        ->setLabel('Favourite Sports')
        ->setMinValue(3)
        ->setMaxValue(3);


While it's nice when you can squeeze by without needing to write a custom validator, there is nothing wrong with writing one when you need to do something slightly out of the ordinary.

This sounds like one of those cases.

0

精彩评论

暂无评论...
验证码 换一张
取 消