ZF2 Form getData returns unvalidated data

1.4k Views Asked by At

I just can't get my first ZF2 form to work! Here is the abbreviated controller action to demonstrate my workflow:

$viewData['form'] = $form = new InstituteEditForm();
$form->setInputFilter(new InstituteInputFilter());
$defaultValues = ...;
$form->populateValues($defaultValues);
if ($request->isPost()) {
    $form->setData($request->getPost());
    if ($form->isValid()) {
        print_r('VALID<br/>');
        var_dump($form->getData());
    } else {
        print_r('INVALID<br/>');
        var_dump($form->getMessages());
        var_dump($form->getData());
    }
}
return new ViewModel($viewData);

The InstituteInputFilter defines Inputs with Filters and Validators for some elements, but not for all. The problem is, that in case the form validates fine, form->getData() returns all values, not just those that have an Input attached, i.e. it returns unvalidated data. This should not be the case, should it?

Thank you so much!

2

There are 2 best solutions below

2
On

the normal step to setup a form is the following below. i comment the code so you should have no problem to understand what method is used for. your main error is that you don't bind the default values to the form class.

$defaultValues = .....; // call db entity from db or whatever

$form = new \MyModule\Form\InstituteEditForm();
$form->setInputFilter(new InstituteInputFilter());

// bind the default values belong to this form
$form->bind($defaultValues);

if( $this->getRequest()->isPost() )
{
    // ok post now setup the post values to the form
    $form->setData($this->getRequest()->getPost());

    if( $form->isValid() )
    {
        $validatedFormData = $form->getData();

        // update entity in db or whatever
        // $db->update($validatedFormData);
        // success messages, redirect...

    } else {

        // uuppps some fields contain errors
        $form->populateValues($this->getRequest()->getPost());

        // get all form errors
        $errorMessages = $form->getMessages();
    }
}
0
On

I've found out, that there is a setting in ZF2.3.1 to attach InputFilters by default, such that any form elements simply pass it, although I have NOT defined any validation. Simply setting $form->setUseInputFilterDefaults(false) yields the behaviour I was expecting: only those form elements that I have attached an Input to, may pass validation. Thus, no unvalidated data is returned by $form->getData.