Issues

ZF-11709: $request->isPost($formName) to check for submitted form

Description

I see in all the examples


class SomeController {
function someAction()
{
    $request = $this->getRequest();
    $form = new CustomForm();
    if($request->isPost()) {
        $form->populate($request->getPost());
        .... do stuff here
    }
    $this->view->form = $form;
}
}

This works fine all the times... almost.

If there's a _forward to someAction by another controller/action that received a POST as well (for example, a login controller/action), the someAction processes the original form, not its own form. It would be handy (and good practice) to actually check if the processed form is indeed the intended form.

Form name is not trasmitted over POST, but we can anyway have Zend_Controller_Request_Http::isPost() check for some hidden field of specific name:


    /**
     * Was the request made by POST?
     * 
     * @param string|bool $fieldName
     * @return boolean
     */
    public function isPost($requiredField = false)
    {
        if ('POST' != $this->getMethod())
            return false;
             
        if($requiredField === false)
            return true;

        return $this->__isset($requiredField);
      
    }

so a simple if($this->getRequest()->isPost('someform')) would do the trick. Of course it is up to the form creator to identify a form field (hidden input, submit button name, or similar) that is unique to that form.

The same purpose could be achieved with more precision by creating a specific form element (hidden input text) reporting the (md5?) form class name.

Comments

IMO, this (determining whether the right fields were submitted) is part of form validation and should be the responsibility of the application, not the framework.

I concur with Adam. If there's a possibility of multiple forms, or forms targeted at different actions of the same request, you should be namespacing them -- usually this is done by grouping all fields of a form under the form's name ("login[user]", "login[password]" vs "comment[subject]", "comment[body]"). This is logic that you as a developer need to perform -- not the framework (though the framework enables this practice in Zend_Form).