The definitive guide of Symfony 1.2

6.6. Validation and Error-Handling Methods

Note The features described in this section are deprecated in symfony 1.1 and only work if you enable the sfCompat10 plugin.

Validating the action input--mostly request parameters--is a repetitive and tedious task. Symfony offers a built-in request validation system, using methods of the action class.

Let's start with an example. When a user makes a request for myAction, symfony always looks for a method called validateMyAction() first. If it is found, then symfony executes it. The return value of this validation method determines the next method to be executed: if it returns true, then executeMyAction() is executed; otherwise, handleErrorMyAction() is executed. And, if in the latter case, handleErrorMyAction() doesn't exist, symfony looks for a generic handleError() method. If that doesn't exist either, it simply returns sfView::ERROR to render the myActionError. php template. Figure 6-2 depicts this process.

The validation process

Figure 6.2 The validation process

So the key to validation is to respect the naming conventions for the action methods:

  • validateActionName is the validation method, returning true or false. It is the first method looked for when the action ActionName is requested. If it doesn't exist, the action method is executed directly.
  • handleErrorActionName is the method called when the validation method fails. If it doesn't exist, the Error template is displayed.
  • executeActionName is the action method. It must exist for all actions.

Listing 6-27 shows an example of an action class with validation methods. Whether the validation passes or fails in this example, the myActionSuccess.php template will be executed, but not with the same parameters.

Listing 6-27 - Sample Validation Methods

class mymoduleActions extends sfActions
{
  public function validateMyAction($request)
  {
    return $request->getParameter('id') > 0;
  }

  public function handleErrorMyAction()
  {
    $this->message = "Invalid parameters";

    return sfView::SUCCESS;
  }

  public function executeMyAction()
  {
    $this->message = "The parameters are correct";
  }
}

You can put any code you want in the validate() methods. Just make sure they return either true or false. As it is a method of the sfActions class, it has access to the sfRequest and sfUser objects as well, which can be really useful for input and context validation.

You could use this mechanism to implement form validation (that is, control the values entered by the user in a form before processing it), but this is the type of repetitive task for which symfony provides automated tools, as described in Chapter 10.