Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zend Framework 2 RC3 Zend\Form#getData()

I wonder if I'm doing something wrong or if this is a bug in ZF2: When i'm trying to set some data on a form, validate it and retrieve the data it's just an empty array.

I extracted this code from some classes to simplify the problem

    $form = new \Zend\Form\Form;
    $form->setInputFilter(new \Zend\InputFilter\InputFilter);
    $form->add(array(
        'name' => 'username',
        'attributes' => array(
            'type'  => 'text',
            'label' => 'Username',
        ),
   ));

   $form->add(array(
        'name' => 'submit',
        'attributes' => array(
            'type'  => 'submit',
            'value' => 'Register',
        ),
    ));

    if ($this->getRequest()->isPost()) {

        $form->setData($this->getRequest()->getPost()->toArray());
        if ($form->isValid()) {

            echo '<pre>';
            print_r($form->getData());
            print_r($form->getMessages());
            echo '</pre>';
        }
    }

both print_r()s show empty arrays. I don't get any Data out of the form as well as no messages. Is it my fault or ZF2's?

like image 552
Andreas Linden Avatar asked Aug 10 '12 07:08

Andreas Linden


1 Answers

Thanks to @SamuelHerzog and @Sam, the form needs inputFilters for all elements. In the case of the form described in the question this short code is enough to get it work at all.

    $inputFilter = new InputFilter();
    $factory     = new InputFactory();

    $inputFilter->add($factory->createInput(array(
        'name'     => 'username'
    )));

    $form->setInputFilter($inputFilter);

It's not required to have any rules for the element, it just needs to be added to the inpoutFilter to work basically. By default any element has the required flag and must not be a blank value.

like image 99
Andreas Linden Avatar answered Oct 06 '22 01:10

Andreas Linden