My First Craft CMS Module

Using an Event to Customize the Craft Control Panel

We add some feature code to the module to add a nav item to the Craft control panel.

For this exam­ple mod­ule, we want to add a con­trol pan­el nav item that is a quick link to our Pod­cast entries list­ing page in the Con­trol Pan­el. We’ll lever­age the sim­plic­i­ty of a mod­ule and the event for reg­is­ter­ing 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 avail­able to us in Craft to inject our own nav item into the con­trol pan­el side bar. This event is called EVENT REGISTER_CP_NAV_ITEMS

We learned how to do this by look­ing through the Craft doc­u­men­ta­tion and the class ref­er­ence. In there we found that it is doc­u­ment­ed how to add a sec­tion 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 side­bar. We add that array of data to the exist­ing navItems array that is avail­able 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'
					];
				}
			);
		}
	}

My First Craft CMS Module is made up of the following videos: