0

Could any of you symfony2 gurus enlighten me as to how I can write a flash message from a symfony2 service?

I thought I had what I needed when I injected the container as below, but apparently not, I get error

Fatal error: Call to undefined method appDevDebugProjectContainer::getRequest() in /var/www/cloudsign_beta/src/BizTV/CommonBundle/Helper/globalHelper.php on line 135

So apparently I can not access the request... If I have to pass that as well from the controller I will soon loose the point of a service, it being unable to do anything by itself =)

<?php
namespace BizTV\CommonBundle\Helper;

use Symfony\Component\DependencyInjection\ContainerInterface as Container;
use Doctrine\ORM\EntityManager as EntityManager;

use BizTV\CommonBundle\Entity\Log;

class globalHelper {    

    private $container;
    private $em;

    public function __construct(Container $container, EntityManager $em) {
        $this->container = $container;
        $this->em = $em;
    }

    public function log($type,$message) {

        // currently $type can be 'success', 'fail' or 'error'.

        $currentUser = $this->container->get('security.context')->getToken()->getUser();
        $currentCompany = $this->container->get('security.context')->getToken()->getUser()->getCompany();

        //if the $type is one that we want to write to the log then create log entity (we don't log failed attempts at operations, but we do log errors.
        if ($type == 'success') {
            $em = $this->em;
            $now = new \DateTime("now");

            $entity  = new Log();
            $entity->setCompany($currentCompany);
            $entity->setExecutor($currentUser);
            $entity->setTime($now);
            $entity->setEventType($type);
            $entity->setEventMessage($message);

            $em->persist($entity);
            $em->flush();
        }

        //flash out the $message message text
        $container = $this->container;
        $session = $container->getRequest()->getSession()->setFlash($type, $message);

    }

}   

1 Answer 1

1
$session = $container->get('request')->getSession()->setFlash($type, $message);

But be careful as you may not be aware of whether request exists or not. A proper way of managing this would be by restricting your service to the request scope.

Sign up to request clarification or add additional context in comments.

2 Comments

Many thanks. I believe request will always exist as this will only be called after a form is validated by symfony.
wouldn't $container->get('session') be shorter?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.