1-33
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
Symfony2 – Franz Jordán 2011<br />
$session->setLocale('fr');<br />
These attributes will remain on the user for the remainder of that user's session.<br />
Flash Messages<br />
You can also store small messages that will be stored on the user's session for exactly one<br />
additional request. This is useful when processing a form: you want to redirect and have a<br />
special message shown on the next request. These types of messages are called "flash"<br />
messages.<br />
For example, imagine you're processing a form submit:<br />
public function updateAction()<br />
{<br />
$form = $this->createForm(...);<br />
$form->bindRequest($this->getRequest());<br />
if ($form->isValid()) {<br />
// do some sort of processing<br />
$this->get('session')->setFlash('notice', 'Your changes were saved!');<br />
return $this->redirect($this->generateUrl(...));<br />
}<br />
return $this->render(...);<br />
}<br />
After processing the request, the controller sets a notice flash message and then redirects.<br />
The name (notice) isn't significant - it's just what you're using to identify the type of the<br />
message.<br />
In the template of the next action, the following code could be used to render<br />
the notice message:<br />
Twig<br />
{% if app.session.hasFlash('notice') %}<br />
<br />
{{ app.session.flash('notice') }}<br />
<br />
{% endif %}<br />
By design, flash messages are meant to live for exactly one request (they're "gone in a flash").<br />
They're designed to be used across redirects exactly as you've done in this example.<br />
The Response Object<br />
The only requirement for a controller is to return a Response object. The Response class is a<br />
PHP abstraction around the HTTP response - the text-based message filled with HTTP headers<br />
and content that's sent back to the client:<br />
// create a simple Response with a 200 status code (the default)<br />
$response = new Response('Hello '.$name, 200);<br />
// create a JSON-response with a 200 status code<br />
$response = new Response(json_encode(array('name' => $name)));<br />
$response->headers->set('Content-Type', 'application/json');<br />
53