Zend Framework 2 RC3 Zend\Form#getData()
Asked Answered
R

1

5

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?

Retroactive answered 10/8, 2012 at 7:53 Comment(6)
Is the array empty or are the values of your forms empty?Hawk
first check print_r($_POST); and print_r($this->getRequest()->getPost(); and provide them to narrow down your problem.Mehalick
@SamuelHerzog both are properly filledRetroactive
I'd guess you are using a standard inputfilter without any rules for username/submit. if there is no data to filter/validate there is no data to output. use the factory of InputFilter to make some rules, add those to your form and look whats happening!Mehalick
Pretty much this and that's what my question was aiming towards. You need to validate your form data. Zend\Form will not output any unvalidated data. The validator (for each forms element) can be empty, but it needs to be validated :)Hawk
post the answer @Sam, I'd say you were first :)Mehalick
R
7

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.

Retroactive answered 13/8, 2012 at 8:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.