ZF-8494: Add method to retrieve only valid values of a Form

Description

Although you often want to access filtered form data only when the complete form is valid, there are lots of use cases in business entities that have state, where the validity of data is only important at the point where a transform in state is requested.

Zend Form however doesn't give me access to only those values that validated during the current request. This feature would however allow to easily save those values already and just wait for the rest to be entered at a later point. The following simple method does this:


class Zend_Form //...
{
//...
    public function getValidValues($data)
    {
        $values = array();
        foreach ($this->getElements() as $key => $element) {
            if (isset($data[$key])) {
                if($element->isValid($data[$key], $data)) {
                    $values[$key] = $element->getValue();
                }
            }
        }
        foreach ($this->getSubForms() as $key => $form) {
            if (isset($data[$key])) {
                $values[$key] = $form->getValidValues($data[$key]);
            }
        }

        return $values;
    }

It allows a pattern of the following kind:


if($this->getRequest()->isPost()) {
    $validValues = $form->getValidValues($this->getRequest()->getPost());
    if(count($validValues)) {
        $service->update($this->getRequest()->getParam('id'), $validValues);
    }
}

Comments

Was implemented and will be in 1.10 release.