Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 37 ยท Modules and Hooks

Plugins and Block Plugins

Learn the Drupal plugin system: plugin types, discovery with attributes, writing a custom block plugin with configuration and cache metadata, and a plugin-manager stand-in.

A plugin is a small, swappable piece of functionality that belongs to a plugin type. Blocks, field types, field widgets, field formatters, Views display and filter handlers, queue workers, image effects, condition checks and many other things are plugins. The idea: the system defines an interface and a manager that discovers implementations, and your module adds a class that implements it. Drupal finds the class by scanning folders, so you register nothing by hand.

The PHP is read-only here. JavaScript stand-ins show how a plugin manager discovers and instantiates implementations.

Anatomy of a plugin

A plugin has three parts:

  1. Plugin type: a manager service (for blocks plugin.manager.block), an interface and a discovery location (src/Plugin/Block/).
  2. Plugin definition: metadata, written as a PHP attribute (Drupal 10.2+ and 11) or a docblock annotation in older code.
  3. Plugin class: the implementation.

Definition by attribute:

PHP
<?php

namespace Drupal\tutorial_notes\Plugin\Block;

use Drupal\Core\Block\Attribute\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\StringTranslation\TranslatableMarkup;

#[Block(
  id: 'tutorial_notes_recent',
  admin_label: new TranslatableMarkup('Recent notes'),
  category: new TranslatableMarkup('Tutorial Notes'),
)]
class RecentNotesBlock extends BlockBase {

  public function build(): array {
    return [
      '#theme' => 'item_list',
      '#items' => ['Plan the sprint', 'Write the module'],
    ];
  }

}

Older code uses an annotation instead:

PHP
/**
 * @Block(
 *   id = "tutorial_notes_recent",
 *   admin_label = @Translation("Recent notes"),
 *   category = @Translation("Tutorial Notes"),
 * )
 */

Both end up as the same plugin definition. Clear the cache and the block appears in Place block. No routing, no hook, no registration.

Node.js Stand-in: plugin discovery and instantiation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Block configuration

A block can have settings that editors fill in when they place it. Override defaultConfiguration(), blockForm() and blockSubmit():

PHP
use Drupal\Core\Form\FormStateInterface;

public function defaultConfiguration(): array {
  return ['limit' => 5] + parent::defaultConfiguration();
}

public function blockForm($form, FormStateInterface $form_state): array {
  $form = parent::blockForm($form, $form_state);
  $form['limit'] = [
    '#type' => 'number',
    '#title' => $this->t('Number of notes'),
    '#default_value' => $this->configuration['limit'],
    '#min' => 1,
    '#max' => 20,
  ];
  return $form;
}

public function blockSubmit($form, FormStateInterface $form_state): void {
  $this->configuration['limit'] = (int) $form_state->getValue('limit');
}

Then use $this->configuration['limit'] in build(). The value is saved with the block placement and travels with exported configuration.

Block access and caching

Control who sees the block with blockAccess():

PHP
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Session\AccountInterface;

protected function blockAccess(AccountInterface $account) {
  return AccessResult::allowedIfHasPermission($account, 'access content');
}

Every block should declare how its output varies. If the list depends on the current user, add a cache context; if it depends on notes, add a cache tag:

PHP
public function getCacheContexts() {
  return ['user'];
}

public function getCacheTags() {
  return ['node_list:note'];
}

Without this, one user's output could be cached and shown to another, or the block would keep showing stale data. See caching and cache tags.

Dependency injection in plugins

Plugins get services through ContainerFactoryPluginInterface:

PHP
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class RecentNotesBlock extends BlockBase implements ContainerFactoryPluginInterface {

  public function __construct(array $configuration, $plugin_id, $plugin_definition, protected NoteManager $notes) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
  }

  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container->get('tutorial_notes.note_manager'));
  }

}

Compare with the controller version in services and dependency injection: the extra arguments are the plugin's own.

Other plugin types you will write

  • Field formatter (src/Plugin/Field/FieldFormatter): how a field value is displayed.
  • Field widget (src/Plugin/Field/FieldWidget): how it is edited.
  • Queue worker (src/Plugin/QueueWorker): background processing for cron.
  • Views field/filter/argument handlers.
  • Condition plugins for block visibility, and Migrate source/process plugins.
  • Action, Filter (text format) and Constraint plugins.

Every one follows the same pattern: a class in the right folder with an attribute naming it.

Node.js Stand-in: a formatter plugin chosen by configuration

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Common mistakes

  • Wrong folder or namespace: a block in src/Block/ is never discovered; it must be src/Plugin/Block/.
  • Duplicate plugin IDs; prefix the ID with the module name.
  • Not clearing the cache after adding a plugin class.
  • Forgetting cache metadata in build().

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where must a custom block plugin class be placed?

    Discovery scans src/Plugin/Block for block plugins.
  2. 2. What identifies a class as a plugin?

    The definition metadata is read by the plugin manager during discovery.
  3. 3. Which method returns the content of a block?

    BlockBase::build() returns a render array.
  4. 4. Why add cache tags and contexts to a block?

    Cache metadata tells Drupal when the block output varies and when it is invalid.

Summary

  • Plugins are discoverable, swappable classes of a defined type, described by attributes (or annotations).
  • A custom block lives in src/Plugin/Block, extends BlockBase and implements build().
  • Configuration, access and cache metadata are methods you override.
  • Use ContainerFactoryPluginInterface for dependency injection.
  • The same pattern builds formatters, widgets, queue workers and more.

Next: The Form API