We add some feature code to the module to add a nav item to the Craft control panel.
For this example module, we want to add a control panel nav item that is a quick link to our Podcast entries listing page in the Control Panel. We’ll leverage the simplicity of a module and the event for registering CP nav items and pass in the data for the nav item we want to add.
To do this we are going to use an Event available to us in Craft to inject our own nav item into the control panel side bar. This event is called EVENT REGISTER_CP_NAV_ITEMS
We learned how to do this by looking through the Craft documentation and the class reference. In there we found that it is documented how to add a section to the CP nav and that we use one of the Craft events to make that happen.
The event we’re using, EVENT_REGISTER_CP_NAV_ITEMS requires that we pass in an array of data that defines the nav item or items that we want to add to the sidebar. We add that array of data to the existing navItems array that is available via the event.
Let’s first set up our event in the code and then we’ll add the data to the array.
<?php
namespace craftquest;
use Craft;
use craft\web\twig\variables\Cp;
use craft\events\RegisterCpNavItemsEvent;
use Yii\base\Module;
use Yii\base\Event;
class CQControlPanel extends Module
{
public function init()
{
Craft::setAlias('@cqcontrolpanel', __DIR__);
parent::init();
Event::on(
Cp::class,
Cp::EVENT_REGISTER_CP_NAV_ITEMS,
function(RegisterCpNavItemsEvent $event) {
$event->navItems[] = [
'url' => 'entries/podcast',
'label' => 'Podcast Episodes',
'icon' => '@cqcontrolpanel/web/img/microphone.svg'
];
}
);
}
}
I am the creator of CraftQuest, a web developer, and former software team manager. I spend most of my time improving CraftQuest with code and courses. When I'm not in front of the computer, I spend my time with my family, and running on the roads and trails of Austin, TX.