[Symfony2.8] flash message

[Symfony2.8] flash message

  • flash message 設計只有使用一次就會消失,因此很適合存使用者提示訊息
  • 舉例來說,你在執行表單 submit
    • use Symfony\Component\HttpFoundation\Request;
      
      public function updateAction(Request $request)
      {
          // ...
      
          if ($form->isSubmitted() && $form->isValid()) {
              // do some sort of processing
      
              $this->addFlash(
                  'notice',
                  'Your changes were saved!'
              );
              // $this->addFlash() is equivalent to $request->getSession()->getFlashBag()->add()
      
              return $this->redirectToRoute(...);
          }
      
          return $this->render(...);
      }
      

       

    • 注意: 通常會使用 notice, warning 和 error 當作 key 去區別不同種類的 flash messages,但是實際上你可以使用任何你想使用的 key
  • 在 template 的下一頁,去從 session 取得任何的 flash messages
    • {# app/Resources/views/base.html.twig #}
      
      {# you can read and display just one flash message type... #}
      {% for flash_message in app.session.flashBag.get('notice') %}
          <div class="flash-notice">
              {{ flash_message }}
          </div>
      {% endfor %}
      
      {# ...or you can read and display every flash message available #}
      {% for type, flash_messages in app.session.flashBag.all %}
          {% for flash_message in flash_messages %}
              <div class="flash-{{ type }}">
                  {{ flash_message }}
              </div>
          {% endfor %}
      {% endfor %}
      

       

    • End