ZF2: allow empty fieldset, but validate if least one is filled out

 ̄綄美尐妖づ 提交于 2019-12-07 07:11:46

问题


I have defined a fieldset for phone numbers. This contains fields "type" (private, Office mobile ...) and "number". The Input filter for number is "required => true":

``

class PhoneFieldset extends BaseFieldset implements InputFilterProviderInterface
{

  public function __construct()
  {
    parent::__construct('phones');

    $this->setHydrator(new DoctrineHydrator($this->getEntityManager(), 'HtsBase\Entity\Phone'))
            ->setObject(new Phone());

    $this->add(array(
        'type' => 'DoctrineORMModule\Form\Element\EntitySelect',
        'name' => 'type',
        'options' => array(
            'label' => 'Type',
            'empty_option' => '',
            'object_manager' => $this->getEntityManager(),
            'target_class' => 'HtsBase\Entity\OptionlistPhoneType',
            'property' => 'name',
        ),
        'attributes' => array(
            #'id' => 'type',
            'class' => 'input-medium',
        ),
    ));

    $this->add(array(
        'name' => 'number',
        'options' => array(
            'label' => 'Number',
        ),
        'attributes' => array(
            'type' => 'text',
            #'id' => 'number',
            'class' => 'input-medium',
            'maxlength' => '25',
            'autocomplete' => 'off',
        ),
    ));
  }

  public function getInputFilterSpecification()
  {
    return array(
        'type' => array(
            'required' => false,
        ),
        'number' => array(
            'required' => true,
            'filters' => array(
                array('name' => 'StringTrim'),
            ),
            'validators' => array(
                array(
                    'name' => 'StringLength',
                    'options' => array(
                        'encoding' => 'UTF-8',
                        'max' => 25,
                    ),
                ),
            ),
        ),
    );
  }

``

Can i attach a validator/filter to the entire fieldset? So that if "type" AND "number" are empty the fieldset is valid, but validate if least one is filled out?


回答1:


I found an easy to use solution, although I don't use the form any more I now heavily use the InputFilter and still needed the same stuff. But found an easy solution

The AbstractFilterValidator, my own implementation

abstract class AbstractFilterValidator extends AbstractValidator
{
    /**
     * Returns true if and only if $value meets the validation requirements
     *
     * If $value fails validation, then this method returns false, and
     * getMessages() will return an array of messages that explain why the
     * validation failed.
     *
     * @param  mixed $value
     * @return bool
     * @throws Exception\RuntimeException If validation of $value is impossible
     */
    public function isValid($value)
    {
        $this->setValue($value);
        $filter = $this->buildFilter();
        $filter->setData($value);

        if (!$filter->isValid()) {
            $this->abstractOptions['messages'] = $filter->getMessages();
            return false;
        }
        return true;
    }

    /**
     * @return array
     */
    public function getMessages()
    {
        return $this->abstractOptions['messages'];
    }

    /**
     * @return InputFilter\InputFilter
     */
    abstract protected function buildFilter();
}

Old answer

Although you were using the InputFilterProviderInterface, I used Zend\InputFilter\InputFilter and wanted the same as you. If the fieldset was not filled in, validate true.

To do this I replace isValid with the following;

public function isValid()
{
    $values = array_filter($this->getRawValues());
    if (empty($values)) {
        return true;
    }

    return parent::isValid();
}

It simply filters the array from all empty array keys, see docs for info about that. Then a check if the $values is empty, and if so return true. Else the validators are called.


Well I needed something again but needed a decent solution. Still no luck finding a good one, so I wrote the following code.

<?php
namespace Application\InputFilter;

use Zend\InputFilter as ZFI;

class InputFilter extends ZFI\InputFilter
{
    private $required = true;

    /**
     * @return boolean
     */
    public function isRequired()
    {
        return $this->required;
    }

    /**
     * @param boolean $required
     *
     * @return $this
     */
    public function setRequired($required)
    {
        $this->required = (bool) $required;
        return $this;
    }

    /**
     * @return bool
     */
    public function isValid()
    {
        if (!$this->isRequired() && empty(array_filter($this->getRawValues()))) {
            return true;
        }

        return parent::isValid();
    }
}

github gist

You can now simply call setRequired(false) on a InputFilter



来源:https://stackoverflow.com/questions/18382738/zf2-allow-empty-fieldset-but-validate-if-least-one-is-filled-out

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!