Java 2 Ada

Fixing the setError and hasError migration issue in Symfony 1.2

By stephane.carrez 1 comments

Foreword on error management in the controller and the view

The controller verifies the form parameters and it can check some error message. For this, Symfony 1.0 was providing the setError method that you use as follows:

$this->getRequest()->setError('username',
  "Sorry, usernames may contain only letters... and dashes.");

Then, in the view template file, you would use the form_error helper to check and report the error message.

<div class="username">
  <label for="username">User name: </label>
  <div class="content">
  <?php echo form_error('username') ?>
  <?php echo input_tag('username') ?>
</div>

The goal is to keep the controller and the view as simple as possible by using the same mechanisms. Here is how in two steps.

Step 1: Provide your own sfWebRequest

First, we override the sfWebRequest to implement the missing operations and we use the setAttribute method to associate the message with the error field. To avoid conflicts with other attributes, the error fields are prefixed with error_.

class myRequest extends sfWebRequest {
    public function hasError($name) {
        return $this->getAttribute("error_" . $name) != null;
    }
    public function setError($name, $msg) {
        $this->setAttribute("error_" . $name, $msg);
    }
    public function getError($name) {
        return $this->getAttribute("error_" . $name);
    }
}

Step 2: Update factories.yml

Now we have to tell Symfony to use our own request class:

all:
  request:
    class: myRequest

Then, clear the symfony cache by running the command:

$ symfony cc

Conclusion

The fix is really simple and if you find other methods that you use and have been removed (hasErrors, getErrors, ...) you just have to add them to you request class!

Add a comment

To add a comment, you must be connected. Login

1 comments

lohana.8@gmail.com
Lohana on 2009-11-26 15:37:32 said:

Muchas Gracias! Tus indicaciones me han ayudado mucho!