0
votes

I just moved from zf1 to zf2 and some simple task are giving me a headache. I have some filters on my form. Filters are being run on form isValid function andafter this function been run, I expected filtered data to be rebind to the form.

I an using zend framework 2.2.7

This is my controller code:

<?php

namespace Test\Controller;

use Test\Entity\Product;
use Test\Form\CreateProduct;
use Zend\Mvc\Controller\AbstractActionController;

class TestController extends AbstractActionController
{

    public function indexAction()
    {
      $form = new CreateProduct();
         $product = new Product();
         $form->bind($product);

         $request = $this->getRequest();
         if ($request->isPost()) {
             $form->setData($request->getPost());

             if ($form->isValid()) {
                 var_dump($product);
             }
             $form->bind($product); // manual rebind seems to work but look hackish 

         }

         return array(
             'form' => $form,
         );
    }
}
1
I understand your need for applying filters even when the data is not valid. But anyways when you will submit again, its going to go through the isValid() method call and apply the filters. So at the end, you do get filtered data. - Kunal Dethe
Yeah my model have filtered data but values which are on the form are still data which been posted without filter being apply. - Krzysztof Lis

1 Answers

1
votes

if you like to "rebind" the data back to the form (after the validation fail) use $form->populateValues()

$request = $this->getRequest();
if( $request->isPost() )
{
    if( $form->isValid() )
    {
        $validatedFormData = $form->getData();
        // do something

    } else {

        // populate posted values to form
        $form->populateValues($request->getPost());

        // fetch form errors $form->getMessages()
        // whatever
    }
}