ZF2 using inputFilter

1.1k views Asked by At

I wonder what I've made wrong, I want to save in db some values whats not come form POST or GET:

public function saveAction()
    {
        $wikiTable = $this->getServiceLocator()->get('WikiTable');

        $data = array('source' => $someVal);

        $form = new WikiForm();
        $inputFilter = new \MyApp\Form\WikiFilter();
        $form->setInputFilter($inputFilter);
        $form->setData($data);
        $this->saveWiki($form->getData());
        //$this->saveWiki($data);                                    
    }

WikiFilter:

       $this->add(
            array(
                'name' => 'source',
                'required' => false,
                'filters' => array(
                    array('name' => 'StripTags'),
                    array('name' => 'StringTrim'),
                )
            )
        ); 

And Form:

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

In response I recive error:

Zend\Form\Form::getData cannot return data as validation has not yet occurred

1

There are 1 answers

0
Velixir On BEST ANSWER

After this line:

$form->setData($data);

You need to put the rest of your code into something like this:

if($form->isValid()){
   $this->saveWiki($form->getData());
}

Otherwise your form isn't validated and you won't get any data back from it by calling $form->getData()

So whenever you work with a form (not matter if the data come from a POST request or not) make sure to call the function isValid() on the form variable because otherwise you won't get the data back and you will get the error you wrote before