Fixing the setError and hasError migration issue in Symfony 1.2
By Stephane Carrez on Sunday, May 17 2009, 22:10 - php - Permalink
After the migration of your Symfony project from 1.1 to 1.2, you may get several errors about the setError and hasError method missing from the sfWebRequest class. Indeed, these operations have been removed. You can use the sfCompat10Plugin but if you don't want to activate this plugin you are stuck.
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!
Comments
Muchas Gracias! Tus indicaciones me han ayudado mucho!