Home » PHP » Zend Framework 2 » The mystery of missing Form->getData() values in Zend Framework 2

The mystery of missing Form->getData() values in Zend Framework 2

After taking a short break from Zend Framework 2 I started working on a new project in it. I created a Form class that looks like:

The problem arose when I validated the form and tried to access the data in the controller:

However, for some reason, the output of $data was missing values, something of this sort:

So, the getData() keys were present, but values were missing!

It took me a while to figure out what’s going on. In order to validate the form, Zend Framework 2 calls getInputFilter on it. However, it does not store the resulting InputFilter, but rather calls this method again whenever it needs it – essentially overwriting any data put into it by $form->setData($postData);

The solution was to store form’s InputFilter as a static variable. The code now looks like this and behaves as expected:

Output of getData() looks like:

Looks like a bug at the first glance, but I suppose this behavior allows for bigger flexibility when validating forms. I still have to find the good use for it, but oh well…

2 thoughts on “The mystery of missing Form->getData() values in Zend Framework 2

  1. This is actually not a very good solution (though it works), since you should avoid using static variables like this.
    A better solution would be something like this:

    inputFilter) {

    $inputFilter = new InputFilter();

    $fullName = new Input('name');
    $v = new ValidatorChain();
    $v->attach(new StringLength(array('min' => 3)));
    $fullName->setValidatorChain($v);
    $fullName->setRequired(true);
    $inputFilter->add($fullName);

    $email = new Input('email');
    $email->setRequired(true);
    $v = new ValidatorChain();
    $v->attach(new EmailAddress());
    $email->setValidatorChain($v);
    $inputFilter->add($email);

    // Make sure we store $inputFilter as a static variable
    $this->inputFilter = $inputFilter;
    }
    return $this->inputFilter
    }
    }

    This way the $inputFilter can be accessed in child classes (since it’s protected) and you’re avoiding any static access.

  2. I am trying to find if there is a solution to fix this issue with Annotations…

    Any idea ?

Leave a Reply

Your email address will not be published. Required fields are marked *