Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate multiply select using Zend Framework 2

I am trying to validate a multiply select using input filter, but every time I see a error. The error is "notInArray":"The input was not found in the haystack".(I use ajax but it doesn`t metter). I will show part of my code to be more clear.

in Controller:

if ($request->isPost()) {
            $post = $request->getPost();
            $form = new \Settings\Form\AddUserForm($roles);// 
            $form->get('positions')
                         ->setOptions(
                                 array('value_options'=> $post['positions']));

//.... more code...

When I put print_r($post['positions']); I see: array(0 => 118, 1 => 119)

in ..../form/UserForm.php I create the multiply element

$this->add(array(
                'type' => 'Zend\Form\Element\Select',
                'attributes' => array(
                    'multiple' => 'multiple',
                    'id' => 'choosed_positions',
                ),
                'required' => false,
                'name' => 'positions',



        ));

and in the validation file the code is:

$inputFilter->add($factory->createInput(array(
                        'name' => 'positions',
                        'required' => false,
                        'validators' => array(
                            array(
                                'name' => 'InArray',
                                 'options' => array(
                                    'haystack' => array(118,119),
                                    'messages' => array(
                                        'notInArray' => 'Please select your position !'
                                    ),
                                ),
                            ),
                        ),

What can be the reason every time to see this error, and how I can fix it?

like image 431
Anton_Sh Avatar asked Oct 21 '22 08:10

Anton_Sh


1 Answers

By default selects have attached InArray validator in Zend Framework 2.

If you are adding new one - you will have two.

You should disable default one as follow:

$this->add(array(
    'type' => 'Zend\Form\Element\Select',
    'options' => array(
        'disable_inarray_validator' => true, // <-- disable
    ),
    'attributes' => array(
        'multiple' => 'multiple',
        'id' => 'choosed_positions',
    ),
    'required' => false,
    'name' => 'positions',
));

And you should get rid of the additional error message. Please let us know if that would helped you.

like image 157
Tomasz Kuter Avatar answered Nov 01 '22 15:11

Tomasz Kuter