Wednesday, March 19, 2014

Custom page & controller in Sonata Admin Bundle

I was stuck for a while trying to figure out how to get my own page into the admin backend of the Sonata Admin Bundle. Specifically, I wanted to have a link in the top menu bar to a page that is created by a controller of mine.

Let's assume that our bundle is the AcmeDemoBundle, residing in the src/Acme/DemoBundle/ folder, which is where most of the following files are in as well.

The first step was to extend the standard_layout.html.twig from the SonataAdminBundle by creating a file here: Resources/views/standard_layout.html.twig

This file contains:

{% extends 'SonataAdminBundle::standard_layout.html.twig' %}
{% block top_bar_after_nav %} 
        <a href="{{ path('acme_demo_hello_index', {'name': 'World'}) }}">
{% endblock %}

Enable this file by adding this configuration to your config.yml:

        layout: AcmeDemoBundle::standard_layout.html.twig

You can now create the Controller/HelloController.php with an indexAction function like so:

namespace Acme\DemoBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

 * Hello controller.
 * @Route("/admin/hello")
class HelloController extends Controller
     * @Route("/{name}")
     * @Template()
    public function indexAction($name)
        $admin_pool = $this->get('sonata.admin.pool');
        return array(
            'admin_pool' => $admin_pool,
            'name' => $name


finally you need to create the template Resources/views/Hello/index.html.twig

{% extends 'AcmeDemoBundle::standard_layout.html.twig' %}

{% block content %}
    Hello {{ name }}!
{% endblock %}

PS: Having written this, I also stumbled upon this StackOverflow question wherein two other solutions are discussed:


r00t said...

this is the easiest way to add a custom page to sonata admin.
is there a way to add the newly added route to the navigation without hardcoding the base theme ?

Wojciech Błoszyk said...

Nice post. I used it in my project. I make one change in template.

{% extends admin_pool.getTemplate('layout') %}

malainine abba said...

thnx for the post
my question is : after installing a new bundle how can i integrate in sonata admin interface ?