Forms Error Catching and Displaying in Symfony
<?php
if ($error) {
$this->getRequest()->setError('userName', 'The user Name field cannot be left blank');
$this->getRequest()->setError('email', 'The Email field cannot be left blank');
return false;
}
?>
Return false is important for returning to the same form, from where you get data for analyzing errors.
In template you will show errors like this:
<?php if ($sf_request->hasErrors()): ?> <p>The data you entered seems to be incorrect. Please correct the following errors and resubmit:</p> <ul> <?php foreach($sf_request->getErrors() as $name => $error): ?> <li><?php echo $name ?>: <?php echo $error ?></li> <?php endforeach; ?> </ul> <?php endif; ?>
Important:
If you are using forward('module', 'action') after setting error (setError()), then it is available in form errors
(hasError()). But these errors will be unavailable then you redirect. If you have set any flash variable ($this->setFlash())
then you can use it in both forward() and redirect() cases.
You have shorthand form for using form errors in template/form.
Instead of writing :
<?php
If ($sf_request->hasError('name')) {
echo $sf_request->getError('name');
}
?>
<?php
use_helper('Validation');
echo form_error('name'); // error if error occurs
?>
message in case validation failed.
Possibly Related posts:

