Cms: Plugin Dev: RegisterCpNavItemsEvent

Created on 17 Jul 2017  路  3Comments  路  Source: craftcms/cms

Description

Attempting to allow my plugin to display as a navigation element in the CP area but I can't get it to work.

I used Redirect as a working example and I've included the code I borrowed below.

Plugin is installed and is working as it should. I can navigate to the CP index page but it will not display the icon and nav element in the sidebar.

I didn't see this anywhere in the docs (I could have missed it) so I'm posting here.

Steps to reproduce

  1. Germinated plugin scaffold from https://pluginfactory.io/
  2. Added the following code to the plugin:

    use craft\events\RegisterCpNavItemsEvent;
    
    // ...
    
    public function getCpNavItem()
    {
        return [
            'url'=> 'pluginurl',
            'label'=>Craft::t('plugin', 'Plugin'),
            'icon' => 'icon'
        ];
    }
    

Additional info

  • Craft version: Craft CMS 3.0.0-beta.22
  • PHP version: 7.0.15
  • Database driver & version: MySQL 5.6.35
  • Plugins & versions: This custom plugin, Redirect as an example
question

All 3 comments

Only usage example we currently have for registering custom CP nav items is in the Updating Plugins for Craft 3 guide:

use craft\events\RegisterCacheOptionsEvent;
use craft\utilities\ClearCaches;
use yii\base\Event;

Event::on(ClearCaches::class, ClearCaches::EVENT_REGISTER_CACHE_OPTIONS, function(RegisterCacheOptionsEvent $event) {
    $event->options[] = [
        'key' => 'drink-images',
        'label' => \Craft::t('drinks', 'Drink images'),
        'action' => \Craft::$app->path->getStoragePath().'/drinks'
    ];
});

(The Event::on() call should go in your plugin鈥檚 init() method.)

I don't think PluginFactory.io currently has an option for creating boilerplate CP nav item code like this though - guessing you added that function yourself, or found it in a Craft 2 plugin.

I think maybe @brandonkelly copied the wrong code sample, it should be:

// New:
use craft\events\RegisterCpNavItemsEvent;
use craft\web\twig\variables\Cp;
use yii\base\Event;

Event::on(Cp::class, Cp::EVENT_REGISTER_CP_NAV_ITEMS, function(RegisterCpNavItemsEvent $event) {
    if (\Craft::$app->user->identity->admin) {
        $event->navItems['foo'] = [
            'label' => \Craft::t('myplugin', 'Utils'),
            'url' => 'utils'
        ];
    }
});

Doh, correct, thanks @khalwat

Was this page helpful?
0 / 5 - 0 ratings