2013-01-22 22 views
11

Sto provando ad impostare Flash nel mio controller, quindi check in TWIG se è stato impostato un Flash. Il mio problema è che TWIG riporta sempre che il mio Flash non è stato impostato e non sono sicuro del perché.Symfony - Impostazione Flash e controllo in TWIG

Controller:

$session->getFlashBag()->add('error', 'Does Not Exist'); 

TWIG:

{{ dump(app.session.hasFlash('error')) }} //outputs false 
{{ dump(app.session.getFlashBag().get('error')) }} //outputs false 

risposta

47

controller

$this->get('session')->getFlashBag()->set('error', 'Does Not Exist'); 

or 

$this->get('session')->getFlashBag()->add('error', 'Does Not Exist'); 

In Twig

{% for flashMessage in app.session.flashbag.get('error') %} 

    {{ flashMessage }} 

{% endfor %} 

FYI: Doc

+0

ho provato, ma quando ho '{{dump (flashMessage)}}' In Twig, io non vedo nulla nemmeno appaiono sullo schermo. – Jon

+1

Il precedente che ha lavorato al controller ha creato una nuova sessione tramite '$ session = new Session();'. Dovrei riferirmi alla sessione tramite '$ session' invece di' $ this-> get ('session') '? – Jon

+0

Nm, ha funzionato magnificamente. – Jon

10
In Controller : 
    $this->get('session')->getFlashBag()->add('error', "User does not exists."); 
In View : 
{% for type, messages in app.session.flashbag.all() %} 
    {% for message in messages %} 
    {% if type == 'error' %} 
      {{ message }} 
    {% endif %} 
    {# Or even with css class rendering: 
    <div class="flash-{{type}}">{{message}}</div> 
    #} 
    {% endfor %} 
{% endfor %} 
4

Vale la pena notare che in Symfony 3.3 e versioni successive possiamo usare la versione semplificata app.flashes(). Esempio:

{% for message in app.flashes('notice') %} 
    <div class="flash-notice"> 
     {{ message }} 
    </div> 
{% endfor %} 

Source

Problemi correlati