jueves, 11 de noviembre de 2010

Using Flash Messages in Symfony

Symfony has a very cool way to handle states. The traditional way would be to declare a variables in the session and then eliminate it. With flash messages you create them a they are dropped in the next request.
When you generate a module using the doctrine:generate-module task you don't get any message telling you the result of your saves.
We're going to show you how to add a message after a record was successfully saved.

Creating a Partial

First create a globlal partial at myproject/apps/myapplication/templates/_flahes.php with the following code:
<?php if ($sf_user->hasFlash('notice')): ?>
<div class="notice"><?php echo __($sf_user->getFlash('notice'),
array(), 'sf_admin') ?></div>
<?php endif; ?>

<?php if ($sf_user->hasFlash('error')): ?>
<div class="error"><?php echo __($sf_user->getFlash('error'),
array(), 'sf_admin') ?></div>
<?php endif; ?>

Editing the _form.php Partial

Open your myproject/apps/myapplication/modules/mymodule/templates/_form.php and add the partial and the i18n helper.
<?php use_helper('I18N') ?>
<?php use_stylesheets_for_form($form) ?>
<?php use_javascripts_for_form($form) ?>
<?php include_partial('global/flashes') ?>

Add the Flash Message in the Action

Open your myproject/apps/myapplication/modules/mymodule/actions/actions.class.php, find the processForm function and add the flash message as shown:

protected function processForm(sfWebRequest $request, sfForm $form) {
$form->bind($request->getParameter($form->getName()),
$request->getFiles($form->getName()));
if ($form->isValid()) {
$repair_request = $form->save();
$this->getUser()->setFlash('notice', 'The item was updated successfully.');
$this->redirect('repairrequest/edit?id=' . $repair_request->getId());
}
}

Styling the Message

Lets style the message open your main.css file and add the following:
.notice{
font: 11px/24px Verdana, Arial, Helvetica, sans-serif;
background: url(../images/ok.png) no-repeat 4px 4px;
margin: 0px 0px 0px 35px;
padding-left: 23px
}
You'll need an ok.png file to use as an icon.

No hay comentarios:

Publicar un comentario