Building a Craft CMS Dashboard Widget
We create a basic widget, without any content, to get things working before we start to customize it.
Any widgets we create for this module will live in the widgets
directory in our module’s src
directory. Each widget will have a class file.
For this widget, create a class file named DeprectWidget.php
inside of src/widgets
in the Widgetopia module you downloaded from Github (see the earlier video, if you missed that part). We need to get the basic class file set up right now with a namespace, import the base Widget class, and our class definition. The result should look like this:
<?php
namespace craftquest/widgets;
use craft\base\Widget;
class DeprecWidget extends Widget
{
// our code will go here
}
Our first goal is to get our widget to appear on the dashboard. We can then worry about populating it with data about the deprecation errors logged for the site.
To do that, we need to register the widget with Craft via our module. We do that in the module class file. Registering a widget means to access an Event called EVENT_REGISTER_WIDGET_TYPES
that is part of the Dashboard service class.
In the Widgetopia.php
module class file, we need to import the base classes from Craft and Yii and our DeprectWidget
class.
use craft\services\Dashboard;
use Yii\base\Event;
use craft\events\RegisterComponentTypesEvent;
use craftquest\widgets\DeprecWidget;
Then we will create a new class method in the module class file to register our widget(s).
private function _registerWidgets()
{
Event::on(
Dashboard::class,
Dashboard::EVENT_REGISTER_WIDGET_TYPES,
function(RegisterComponentTypesEvent $event) {
$event->types[] = DeprecWidget::class;
}
);
}
We need to call the private method in our class init()
method for the module.
public function init()
{
parent::init();
$this->_registerWidgets();
}
If we reload our dashboard, we’ll get an error that Craft cannot find our widget class. This is because we need to build the autoload files. From the command line, run:
composer dump-autoload -a
And now we should see our widget in the New widget menu on the dashboard!
Building a Craft CMS Dashboard Widget is made up of the following videos: