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 %} 
    <li>
        <a href="{{ path('acme_demo_hello_index', {'name': 'World'}) }}">
            Statistik
        </a>
    </li>
{% endblock %}


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

sonata_admin:
    templates:
        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: http://stackoverflow.com/questions/15966575/sonataadminbundle-display-non-crud-statistics/22507027

3 comments:

Unknown said...

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

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

Unknown said...

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

Unknown said...

https://symfony.com/doc/3.x/bundles/SonataAdminBundle/cookbook/recipe_custom_view.html