1

I'm working on porting a Yii2 component to Craft CMS as a plugin. This Yii2 component provides a debug bar custom panel that I'd like to enable in Craft CMS too.

In classic Yii2 applications, this is done by adding an entry to the modules.debug.panels configuration directive:

'bootstrap' => ['debug'],
'modules' => [
    'debug' => [
        'class' => 'yii\\debug\\Module',
        'panels' => [
            'elasticsearch' => [
                'class' => 'my\\namespace\\DebugPanel',
            ],
        ],
    ],
],

Unfortunately, Craft 3 seems to hardcode this configuration in the craft\web\Application::debugBootstrap() method.

How to add a custom panel to the debugbar in Craft 3?

2

I'm not sure this is the proper way to do it but I got this working.

I used the Yii\Application::EVENT_BEFORE_REQUEST event in my plugin's init() method:

<?php

namespace my\namespace;

use craft\base\Plugin;
use craft\web\Application;

class MyPlugin extends Plugin
{
    public function init()
    {
        Event::on(
            Application::class, 
            Application::EVENT_BEFORE_REQUEST, 
            function() {
                /** @var \yii\debug\Module */
                $debugModule = Craft::$app->getModule('debug');
                
                $debugModule->panels['mycustompanel'] = new DebugPanel(['module' => $debugModule]);
            }
        );
    }
}

At first, I thought about using the yii\base\Controller::EVENT_BEFORE_ACTION event, but in order to work, the Yii2 component needed to add some routes and the EVENT_BEFORE_ACTION event occurs after routing has been done.

Any other event I could think of occurred too early, before Craft had called the craft\web\Application::debugBootstrap() method.

So far it works but if anyone has a suggestion on the proper way to do it, I'm all hears.


Edit 10/05/2020: it looks like I was almost there. I was just missing the id property in the Panel's constructor parameter. Without it, clicking your panel name in the collapsed debug bar won't open straight away on your panel's tab.

It's also important to check that the Debug module is loaded before adding your panel to it. Otherwise users having the debug bar disabled would get errors.

I found out by looking at the code in Ben Croker's Element Panel plugin.

Event::on(
    Application::class,
    Application::EVENT_BEFORE_REQUEST,
    function () {
        /** @var \yii\debug\Module */
        $debugModule = Craft::$app->getModule('debug');

        if ($debugModule) {
            $debugModule->panels['mycustompanel'] = new DebugPanel([
                'id'     => 'mycustompanel',
                'module' => $debugModule,
            ]);
        }
    }
);
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.