1
votes

I give up.

The problem is with the overrided Twig 404 template. It is overrided in a default way by creating an error404.html.twig under the /app/Resources/TwigBundle/views directory.

The template itself does not contain any irregular or complex logic: just a layout with some translated text (|trans) and a menu with several links.

The problem is, that I can't get app.user object (returned as NULL) or current app.request.locale (always returned as default locale) inside this template.

I have even tried to override the twig exception controller and dump a current locale (Request::getLocale()) or get user - the results are the same - default locale and NULL for user.

Then I decided to dig deeper and found a dozens of listeners (locale listeners, exception liteners, ...) and tried to debug/fix/test there, but I didn't proceed any further.

By the way, I have overrided the 500 error page too, and everything is fine there. Well I guess that when 500 error (exception) is thrown, the symfony has already set up user/locale/etc, because it already has got to the target (controller/action) and other listeners been already executed. But 404 error (NotFoundHttpException) is being thrown BEFORE Symfony targets the action...

Some words about project: symfony 2.4.8, doctrine, Gedmo extensions/stof bundle, JMS i18n routing bundle.

Symfony version: v2.4.8 JMS I18n Routing bundle: 1.1.1

Appreciate your help.

2
The problem is resolved (well, as possible). Solution is proposed by devilcius.Dmitry

2 Answers

2
votes

That's the way I do it (at least for 404 templates):

In app/config/routing.yml append:

#always in last position
#------------>
nonexistent_route:
    path:     /{url}
    defaults: { _controller: ACMEDemoBundle:Default:wrongRoute}
    requirements:
        url: ".+"    
#<-----------

The Controller:

namespace ACME\DemoBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class DefaultController extends Controller
{
    ...

    public function wrongRouteAction($url)
    {
        $user = $this->get('security.context')->getToken()->getUser();

        return $this->render('TwigBundle:Exception:error404.html.twig', array("user" => $user, "url" => $url));

    }
}

And in your twig template app/Resources/TwigBundle/views/Exception/error404.html.twig you can access {{ user }}

1
votes

You can create register listener on KernelException event and define any logic you need there. Like this:

use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;

class YourKernelExceptionListener
{
    public function onKernelExcpetion(GetResponseForExceptionEvent $event)
    {
        // if the exception is instance of Symfony NotFoundHttpException
        // you can do whatever you need and render whatever you need
    }
}