Solber
Solber

Reputation: 167

Flash message in symfony 3.4

I'm trying to set flash message from ContactAction then redirect on Homepage, but on it, I can't see my flash message, maybe my session is reset ? Can I have some help, I'm a beginer on Symfony.

CoreController that contain both index and contact functions :

<?php
namespace OC\CoreBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class CoreController extends Controller
{

    public function indexAction()
    {
        $ServiceAdverts = $this->container->get('oc_core.listAdverts');
        $adList = $ServiceAdverts->getListAdverts();

        return $this->render("OCCoreBundle:Core:index.html.twig", array(
        'listAdverts' => $adList
        ));
    }

    public function contactAction()
    {
        $this->addFlash('info', 'Contact page not ready yet !');

        return $this->redirectToRoute('oc_core_homepage');
    }
}

Twig template (homepage) :

{% block body %}

<div>
    Messages flash :
    {% for msg in app.session.flashBag.get('info') %}
        <div class="alert alert-success">
            {{ msg }}
        </div>
    {% endfor %}

</div>
<h2>Liste des annonces</h2>

<ul>
    {% for advert in listAdverts %}
        <li>
            <a href="{{ path('oc_platform_view', {'id': advert.id}) }}">
                {{ advert.title }}
            </a>
            par {{ advert.author }},
            le {{ advert.date|date('d/m/Y') }}
        </li>
    {% else %}
        <li>Pas (encore !) d'annonces</li>
    {% endfor %}
</ul>

<a href="{{ path('oc_core_contact') }}">Contact</a>

{% endblock %}

Upvotes: 1

Views: 6030

Answers (2)

Julesezaar
Julesezaar

Reputation: 3396

Try this, works for me in 3.2 and 3.4

{% for type, flash_messages in app.session.flashBag.all %}
    {% for msg in flash_messages %}
        <div class="alert alert-{{ type }}">
            {{ msg }}
        </div>
    {% endfor %}
{% endfor %}

Another thing is that once you called the flashBag it turns empty so you can't use it twice. Check your code that it hasn't been called on another page right before a second redirect ...

Upvotes: 0

Jason Roman
Jason Roman

Reputation: 8276

Symfony 3.3 made improvements to flash messages so your Twig template should look different. The app.session.flashBag.get() call is now replaced by app.flashes().

So your Twig code would now be:

{% for msg in app.flashes('success') %}
    <div class="alert alert-success">
        {{ msg }}
    </div>
{% endfor %}

Upvotes: 1

Related Questions