Creating blocks using plugins
- Create the src/Plugin/Block directory in your module. This will translate the \Drupal\mymodule\Plugin\Block namespace and allow a block plugin discovery.
-
Create a Copyright.php file in the newly created folder so that we can define the Copyright class for our block :
-
The Copyright class will extend \Drupal\Core\Block\BlockBase:
<?php
/**
* @file
* Contains \Drupal\mymodule\Plugin\Block\Copyright.
*/
namespace Drupal\mymodule\Plugin\Block;
use Drupal\Core\Block\BlockBase;
class Copyright extends BlockBase {
}
-
We extend the BlockBase class, which implements \Drupal\Core\Block\ BlockPluginInterface and provides us with an implementation of nearly all of its methods.
-
Blocks are annotated plugins. Annotated plugins use documentation blocks to provide details of the plugin. We will provide the block’s identifier, administrative label, and category:
<?php
/**
* @file
* Contains \Drupal\mymodule\Plugin\Block\Copyright.
*/
namespace Drupal\mymodule\Plugin\Block;
use Drupal\Core\Block\BlockBase;
/**
* @Block(
* id = “copyright_block”,
* admin_label = @Translation(“Copyright”),
* category = @Translation(“Custom”)
* )
*/
class Copyright extends BlockBase {
}
-
The annotation document block of the class identifies the type of plugin through @Block. Drupal will parse this and initiate the plugin with the properties defined inside it. The id is the internal machine name, the admin_label is displayed on the block listing page, and category shows up in the block select list.
-
We need to provide a build method to satisfy the \Drupal\Core\Block\ BlockPluginInterface interface. This creates the output to be displayed:
<?php
/**
* @file
* Contains \Drupal\mymodule\Plugin\Block\Copyright
*/
namespace Drupal\mymodule\Plugin\Block;
use Drupal\Core\Block\BlockBase;
/**
* @Block(
* id = “copyright_block”,
* admin_label = @Translation(“Copyright”),
* category = @Translation(“Custom”)
* )
*/
class Copyright extends BlockBase {
/**
* {@inheritdoc}
*/
public function build() {
$date = new \DateTime();
return [
‘#markup’ => t(‘Copyright @year© My Company’, [
‘@year’ => $date->format(‘Y’),
]),
];
}
}
The build method returns a render array that uses Drupal’s t function to substitute @year for the \DateTime object’s output that is formatted as a full year.
-
Rebuild Drupal’s cache so that the new plugin can be discovered.
-
In the Footer fourth region, click on Place block
-
Review the block list and add the custom block to your regions, for instance, the footer region. Find the Copyright block, and click on Place block: