Skip to content

Commit

Permalink
It is a form's responsibility to process the request it was submitted…
Browse files Browse the repository at this point in the history
… with

How forms are being validated should not be a task that is part of the
controller action, but should be handled by the form base class as it is
most of the time the same procedure. Now a controller action just sets
up the form to use, calls handleRequest() and acts upon its return value.
(e.g. calling handleRequest() from another form or any redirection)

refs #5525
  • Loading branch information
Johannes Meyer committed Aug 25, 2014
1 parent c93ab79 commit 52534a2
Showing 1 changed file with 55 additions and 0 deletions.
55 changes: 55 additions & 0 deletions library/Icinga/Web/Form.php
Expand Up @@ -190,6 +190,30 @@ public function createElements(array $formData)
return array();
}

/**
* Perform actions after this form was submitted using a valid request
*
* Intended to be implemented by concrete form classes.
*
* @param Request $request The valid request used to process this form
*/
public function onSuccess(Request $request)
{

}

/**
* Perform actions after this form was submitted using an invalid request
*
* Intended to be implemented by concrete form classes.
*
* @param Request $request The invalid request supposed to process this form
*/
public function onFailure(Request $request)
{

}

/**
* Add a submit button to this form
*
Expand Down Expand Up @@ -292,6 +316,37 @@ public function setDefaults(array $defaults)
return parent::setDefaults($defaults);
}

/**
* Process the given request using this form
*
* @param Request $request The request to be processed
*
* @return null|bool True in case the request was handled and valid,
* false if invalid and null if it was not handled
*/
public function handleRequest(Request $request)
{
if (strtolower($request->getMethod()) === $this->getMethod()) {
$formData = $request->{'get' . $request->isPost() ? 'Post' : 'Query'}();
if ($this->wasSent($formData)) {
$this->populate($formData); // Necessary to get isSubmitted() to work
if ($this->isSubmitted()) {
if ($this->isValid($formData)) {
$this->onSuccess($request);
return true;
} else {
$this->onFailure($request);
}
} else {
// The form can't be processed but we want to show validation errors though
$this->isValidPartial($formData);
}

return false;
}
}
}

/**
* Return whether the submit button of this form was pressed
*
Expand Down

0 comments on commit 52534a2

Please sign in to comment.