Skip to content

Instantly share code, notes, and snippets.

@webdevilopers
Last active November 16, 2019 20:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save webdevilopers/7c8c267a51425c91216b to your computer and use it in GitHub Desktop.
Save webdevilopers/7c8c267a51425c91216b to your computer and use it in GitHub Desktop.
Symfony - Inject Session Flash Bag into Service with output and translation in TWIG via app.session
services:
app.bundle.service:
class: AppBundle\Service
arguments:
- "@doctrine.orm.entity_manager"
- "@security.token_storage"
- "@session"
- "@translator.default"
<?php
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class DefaultController extends Controller
{
/**
* @Route("/")
* @Template()
*/
public function indexAction($type)
{
$data = $this->getRequest()->request->all();
$service = $this->get('service');
$service->setData(array('quantity' => 1));
return $this->render('AppBundle:Default:new.html.twig', array());
}
}
Setting initial window surface to %window_surface%&sup2;.: Setze Fensterfläche auf %window_surface%&sup2;
{% for flash_message in app.session.flashbag.get('notice') %}
<div class="flash-notice">
{{ flash_message }}
</div>
{% endfor %}
<?php
use Doctrine\ORM\EntityManager;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Translation\Translator;
class Service
{
private $entityManager;
private $tokenStorage;
private $session;
private $translator;
private $translationDomain = 'foo';
public function __construct(EntityManager $entityManager, TokenStorageInterface $tokenStorage, Session $session, Translator $translator)
{
$this->entityManager = $entityManager;
$this->tokenStorage = $tokenStorage;
$this->session = $session;
$this->translator = $translator;
}
public function addMessage($message, array $parameters = array(), $type = 'notice')
{
$this->session->getFlashBag()->add(
$type, $this->translator->trans($message, $parameters, $this->translationDomain));
}
public function getMessages()
{
return $this->session->getFlashBag()->all();
}
private function setData($data)
{
$windowSurface = 360;
$this->addMessage("Setting initial window surface to {{ window_surface }}&sup2;.", array(
'%window_surface%' => $windowSurface));
}
}
@webdevilopers
Copy link
Author

I think I found the problem @adampiotrowski:
The Flash Bag can only be outputted once!? As soon as you dump it somewhere before the twig template, it will be emptied.

Can this setting be changed? Should it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment