ZF2 passing 0 to a required formfield

684 views Asked by At

Ok, i'm getting a little frustrated over here. According to the code below, it seems impossible to pass '0' to a required formfield in Zend Framework 2 without causing it to get the status 'invalid'.

// FLOAT (0.0)
    if ($type >= self::FLOAT) {
        $type -= self::FLOAT;
        if (is_float($value) && ($value == 0.0)) {
            $this->error(self::IS_EMPTY);
            return false;
        }
    }

    // INTEGER (0)
    if ($type >= self::INTEGER) {
        $type -= self::INTEGER;
        if (is_int($value) && ($value == 0)) {
            $this->error(self::IS_EMPTY);
            return false;
        }
    }

This code is from 'Zend\Validator\NotEmpty' which is invoked by the property 'required=true' in the inputFilterSpecification() method.

Then my question: Why? In my opinion, 0 is a perfectly valid integer and 0.0 is a perfectly valid floating point number.

In addition: How to avoid this validation while keeping the 'required=true'? My field is still required you know.

This is my form element:

$this->add(
    array(
        'name' => 'price',
        'type' => 'Zend\Form\Element\Text',
        'options' => array(
           'label' => 'Price'
        )
   )
);

And this is my inputFilterSpecification:

'price' => array(
    'required' => true,
    'validators' => array(
        array(
            'name' => 'Float',
        ),
    ),
    'filters' => array (
        array(
           'name' => 'Shop\Form\Filter\CurrencyFilter',
        )
    ),
),
1

There are 1 answers

0
ins0 On BEST ANSWER

just extend the validator class from zf2 like this

namespace Application\Validator;

use Zend\Validator\NotEmpty;

class NotEmptyAllowZero extends NotEmpty {

    public function isValid( $value ) {

        $type = $this->getType();

        // allow zero float
        if($type >= self::FLOAT && $value == 0.0) {
            return true;
        }
        // allow integer zero
        if ($type >= self::INTEGER && $value == 0) {
            return true;
        }

        // go on with zend validator
        return parent::isValid( $value );
    }

}

Register the Custom Validator in your Module Config (like Application/Config.php)

'service_manager'    => array(
    'invokables' => array(
        'NotEmptyAllowZero'            => 'Application\Validator\NotEmptyAllowZero'
    )
)

and u can use it as Validator (!not filter)

'price' => array(
    'required' => true,
    'validators' => array(
        array(
            'name' => '\Application\Validator\NotEmptyAllowZero',
        ),
    ),
    'filters' => array (
        array(
            'name' => 'Shop\Form\Filter\CurrencyFilter',
        )
    ),
),