ZF2 : Filedset validation is not working

Ravi

My ZF2 Form Field set validation is not working but form validation is working I have tried same a form validation, but these are not working.

I have implemented InputFilterProviderInterface in field set but it is not working.

Below is my code:

class CompanyCreditLimitFieldset extends Fieldset implements InputFilterProviderInterface {

    protected $_curency = null;
    protected $inputFilter;

    public function __construct($name = null, $options = array()) {
        $this
                ->setHydrator(new ClassMethodsHydrator(false))
                ->setObject(new \Application\Entity\PhvCompanyCurrencyCredit())
        ;

        parent::__construct($name, $options);



        $this->add(array(
            'name' => 'credit_limit',
            'type' => 'text',
            'attributes' => array(
                'id' => 'credit_limit',
                'class' => 'form-control maxlength-simple credit_limit',
                'placeholder' => 'Credit Limit'
            ),
            'options' => array(
                'label' => 'Credit Limit',
            )
        ));

        $this->add(array(
            'name' => 'mininum_balance_limit',
            'type' => 'text',
            'attributes' => array(
                'id' => 'mininum_balance_limit',
                'class' => 'form-control maxlength-simple mininum_balance_limit',
                'placeholder' => 'Minimum Balance Limit'
            ),
            'options' => array(
                'label' => 'Minimum Balance Limit',
            )
        ));
    }


    public function getInputFilterSpecification() {
        return array(
            'credit_limit' => array(
                'filters' => array(
                    array('name' => 'StringTrim')
                ),
                'validators' => array(
                    array('name' => 'NotEmpty')
                )
            ),
            'mininum_balance_limit' => array(
                'filters' => array(
                    array('name' => 'StringTrim')
                ),
                'validators' => array(
                    array('name' => 'NotEmpty')
                )
            ),

        );
    }

}

Form

class AddCompanyForm extends AbstractForm implements InputFilterAwareInterface {

    protected $inputFilter;
    protected $dbAdapter;
    private $_country = null;

    public function __construct($id = null, $name = null) {
        $this->entity = new \Application\Entity\PhvCompany();
        parent::__construct($name);

        $this
                ->setHydrator(new ClassMethodsHydrator(false))
                ->setObject(new \Application\Entity\PhvCompany())
        ;

        $this->__addElements();
    }

    private function __addElements() {
        $this->setAttribute('method', 'post');

        $this->add(array(
            'type' => 'Zend\Form\Element\Collection',
            'name' => 'creditlimitfieldset',
            'options' => array(
                'label' => 'Credit Limits',
                'count' => 3,
                'allow_add' => true,
                'should_create_template' => true,
                'template_placeholder' => '__placeholder__',
                'target_element' => array(
                'type' => 'Application\Form\Fieldset\CompanyCreditLimitFieldset',
                ),
            ),
//             'type' => 'Application\Form\Fieldset\CompanyCreditLimitFieldset',
//             'options' => array('label' => 'Credit Limits',)
        ));


        $this->add(array(
            'name' => 'submit',
            'attributes' => array(
                'type' => 'submit',
                'value' => 'Save',
                'class' => 'btn btn-inline btn-secondary btn-rounded'
            )
        ));




    }

    public function setDbAdapter($dbAdapter) {
        $this->dbAdapter = $dbAdapter;
    }

    public function setInputFilter(InputFilterInterface $inputFilter) {
        throw new \Exception("Not used");
    }

}

Can you please help me to solve this issue.

Adam Lundrigan

Frankly, this type of problem is why I always build a separate InputFilter hierarchy matching the Form structure instead of relying on ZF's "magic" input filter builder. Here's a great article on how to do that:

When working with collections in this manner you'll need to add a CollectionInputFilter to the form's input filter for each Collection form element. That class is completely undocumented IIRC, but you can find an example here and the class here.


I wrote a short script that reproduces what you're seeing:

<?php
<<<CONFIG
packages:
    - "zendframework/zend-form: ^2.0"
    - "zendframework/zend-servicemanager: ^3.0"
    - "zendframework/zend-hydrator: ^2.0"
CONFIG;
// Run this script with Melody: http://melody.sensiolabs.org/


use Zend\Form\Fieldset;
use Zend\InputFilter\InputFilterProviderInterface;
use Zend\Form\Form;

class ChildFieldset extends Fieldset implements InputFilterProviderInterface
{
    public function __construct($name = null, $options = array())
    {
    parent::__construct($name, $options);

    $this->add(array(
        'name' => 'fieldA',
        'type' => 'text',
        'attributes' => array(
            'id' => 'fieldA',
        ),
        'options' => array(
            'label' => 'Field A',
        )
    ));
    }

    public function getInputFilterSpecification()
    {
    return array(
        'fieldA' => array(
            'required'          => true,
            'allow_empty'       => false,
            'continue_if_empty' => false,
            'filters' => array(
                array('name' => 'StringTrim')
            ),
            'validators' => array(
                array('name' => 'NotEmpty')
            )
        ),
    );
    }
}

class ParentForm extends Form
{
    public function __construct($name, array $options)
    {
    parent::__construct($name, $options);

    $this->add(array(
        'type' => 'Zend\Form\Element\Collection',
        'name' => 'childForms',
        'options' => array(
            'label' => 'Child Forms',
            'allow_add' => true,
            'should_create_template' => true,
            'template_placeholder' => '__placeholder__',
            'target_element' => array(
                'type' => 'ChildFieldset',
            ),
        ),
    ));

    $this->add(array(
        'name' => 'submit',
        'attributes' => array(
            'type' => 'submit',
            'value' => 'Save',
        )
    ));
    }
}

$form = new ParentForm('foo', []);

$data = [];
$form->setData($data);
echo "Dataset: " . print_r($data, true) . "\n";
echo "Result: " . ($form->isValid() ? 'valid' : 'invalid');
echo "\n\n--------------------------------------\n\n";


$data = [
    'childForms' => []
];
$form->setData($data);
echo "Dataset: " . print_r($data, true) . "\n";
echo "Result: " . ($form->isValid() ? 'valid' : 'invalid');
echo "\n\n--------------------------------------\n\n";


$data = [
    'childForms' => [
    ['fieldA' => ''],
    ],
];
$form->setData($data);
echo "Dataset: " . print_r($data, true) . "\n";
echo "Result: " . ($form->isValid() ? 'valid' : 'invalid') . "\n\n";
echo "\n\n--------------------------------------\n\n";


$data = [
    'childForms' => [
    ['fieldA' => 'fff'],
    ],
];
$form->setData($data);
echo "Dataset: " . print_r($data, true) . "\n";
echo "Result: " . ($form->isValid() ? 'valid' : 'invalid') . "\n\n";

and when I run it (PHP 7.0.9) I get this:

Dataset: Array
(
)

Result: valid
(wrong)

--------------------------------------

Dataset: Array
(
    [childForms] => Array
    (
    )

)

Result: valid
(wrong)

--------------------------------------

Dataset: Array
(
    [childForms] => Array
    (
        [0] => Array
            (
                [fieldA] => 
            )

    )

)

Result: invalid
(correct!)


--------------------------------------

Dataset: Array
(
    [childForms] => Array
    (
        [0] => Array
            (
                [fieldA] => fff
            )

    )

)

Result: valid
(correct!)

The input filter on the child fieldset is only triggered when the full hierarchy of keys exist in the data. It's not a bug per se, but it's not what you expect to happen.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

ZF2 deleteAction not working

From Dev

Translation is not working with ZF2

From Dev

ZF2 setCookie not working

From Dev

zf2 session validation failed

From Dev

ZF2 - validation within a bootstrap modal

From Dev

ZF2 nested data validation

From Dev

ZF2 translator is not working in controller?

From Dev

ZF2 transalation is not working in form class

From Dev

working with session on zf2 (recover container)

From Dev

ZF2 segment child route not working

From Dev

ZF2 route with prefix in not working for default

From Dev

Zf2 float validation is invalid but validator messages are empty

From Dev

zf2 validation: How can I validate dependent fields?

From Dev

ZF2 + Duplicate Form Validation on composite key

From Dev

ZF2 Form validation - non-overlapping dates and times

From Dev

ZF2 Render Custom Class on Form Validation Error

From Dev

ZF2 + Duplicate Form Validation on composite key

From Dev

ZF2 Captcha validation ignored when using an input filter

From Dev

How to always show single validation message in ZF2 validators?

From Dev

How to input a calculated value after form validation in zf2

From Dev

ZF2 redirect() not working while header location does

From Dev

ZF2 form HTML5 Number element is not working

From Dev

ZF2 Annotation Validators NotEmpty and Int not working?

From Dev

ZF2, exception was raised while creating a listener & Session validation failed

From Dev

Doctrine2 with MS Server pagination and order by not working under ZF2

From Dev

Angular 2 form validation not working

From Dev

ZF2, I18n and dynamic locale not working anymore after update

From Dev

Why did javascript stop working when I implemented ZF2 ACL?

From Dev

ZF2, I18n and dynamic locale not working anymore after update

Related Related

  1. 1

    ZF2 deleteAction not working

  2. 2

    Translation is not working with ZF2

  3. 3

    ZF2 setCookie not working

  4. 4

    zf2 session validation failed

  5. 5

    ZF2 - validation within a bootstrap modal

  6. 6

    ZF2 nested data validation

  7. 7

    ZF2 translator is not working in controller?

  8. 8

    ZF2 transalation is not working in form class

  9. 9

    working with session on zf2 (recover container)

  10. 10

    ZF2 segment child route not working

  11. 11

    ZF2 route with prefix in not working for default

  12. 12

    Zf2 float validation is invalid but validator messages are empty

  13. 13

    zf2 validation: How can I validate dependent fields?

  14. 14

    ZF2 + Duplicate Form Validation on composite key

  15. 15

    ZF2 Form validation - non-overlapping dates and times

  16. 16

    ZF2 Render Custom Class on Form Validation Error

  17. 17

    ZF2 + Duplicate Form Validation on composite key

  18. 18

    ZF2 Captcha validation ignored when using an input filter

  19. 19

    How to always show single validation message in ZF2 validators?

  20. 20

    How to input a calculated value after form validation in zf2

  21. 21

    ZF2 redirect() not working while header location does

  22. 22

    ZF2 form HTML5 Number element is not working

  23. 23

    ZF2 Annotation Validators NotEmpty and Int not working?

  24. 24

    ZF2, exception was raised while creating a listener & Session validation failed

  25. 25

    Doctrine2 with MS Server pagination and order by not working under ZF2

  26. 26

    Angular 2 form validation not working

  27. 27

    ZF2, I18n and dynamic locale not working anymore after update

  28. 28

    Why did javascript stop working when I implemented ZF2 ACL?

  29. 29

    ZF2, I18n and dynamic locale not working anymore after update

HotTag

Archive