From a5168ad2f46264508b93b60c4c21a21384244662 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Fri, 26 Apr 2013 16:48:41 +0200 Subject: [PATCH] fixed example to check if the session exists when getting flash messages to avoid starting sessions when not needed --- book/controller.rst | 24 ++++++++++++++---------- components/http_foundation/sessions.rst | 13 +++++++++++++ quick_tour/the_controller.rst | 8 +++++--- 3 files changed, 32 insertions(+), 13 deletions(-) diff --git a/book/controller.rst b/book/controller.rst index 68f63607979..b2b729b8157 100644 --- a/book/controller.rst +++ b/book/controller.rst @@ -686,19 +686,23 @@ the ``notice`` message: .. code-block:: html+jinja - {% for flashMessage in app.session.flashbag.get('notice') %} -
- {{ flashMessage }} -
- {% endfor %} + {% if app.session.started %} + {% for flashMessage in app.session.flashbag.get('notice') %} +
+ {{ flashMessage }} +
+ {% endfor %} + {% endif %} .. code-block:: html+php - getFlashBag()->get('notice') as $message): ?> -
- $message
" ?> - - + isStarted()): ?> + getFlashBag()->get('notice') as $message): ?> +
+ $message
" ?> + + + By design, flash messages are meant to live for exactly one request (they're "gone in a flash"). They're designed to be used across redirects exactly as diff --git a/components/http_foundation/sessions.rst b/components/http_foundation/sessions.rst index dbd855f4bf0..559d699eae0 100644 --- a/components/http_foundation/sessions.rst +++ b/components/http_foundation/sessions.rst @@ -333,3 +333,16 @@ Compact method to process display all flashes at once:: echo "
$message
\n"; } } + +.. caution:: + + As flash messages use a session to store the messages from one request to + the next one, a session will be automatically started when you read the + flash messages even if none already exists. To avoid that default + behavior, test if there is an existing session first:: + + if ($session->isStarted()) { + foreach ($session->getFlashBag()->get('warning', array()) as $message) { + echo "
$message
"; + } + } diff --git a/quick_tour/the_controller.rst b/quick_tour/the_controller.rst index c11c5473140..67b66b8b60f 100755 --- a/quick_tour/the_controller.rst +++ b/quick_tour/the_controller.rst @@ -141,9 +141,11 @@ next request:: // display any messages back in the next request (in a template) - {% for flashMessage in app.session.flashbag.get('notice') %} -
{{ flashMessage }}
- {% endfor %} + {% if app.session.started %} + {% for flashMessage in app.session.flashbag.get('notice') %} +
{{ flashMessage }}
+ {% endfor %} + {% endif %} This is useful when you need to set a success message before redirecting the user to another page (which will then show the message). Please note that