Home Backend Development PHP Tutorial Drupal 8 Custom Plugin Types

Drupal 8 Custom Plugin Types

Feb 16, 2025 am 10:15 AM

Drupal 8's robust plugin system empowers backend developers with reusable functionality. This article (part one of two) details building a feature enabling custom forms with node entities, allowing configuration of node bundles to utilize various form types alongside node displays. New form types are easily defined by extending a provided base class. (For a complete code example, refer to this repository).

Drupal 8 Custom Plugin Types

This tutorial avoids in-depth plugin mechanics, assuming familiarity with the underlying theory. We'll construct our custom plugin type using two interfaces and six classes—a seemingly large number, but mostly straightforward boilerplate code. Part two will demonstrate attaching these reusable forms to nodes.

Key Concepts:

  • Drupal 8's plugin system facilitates reusable functionality, enabling custom forms for node entities. Node bundles can be configured to use multiple form types within node displays.
  • The plugin manager, essential for plugin discovery and loading, leverages Drupal's default base class for easy extension. All plugins must implement a defined interface.
  • Plugin definitions utilize annotations containing crucial information: the plugin subdirectory, the required interface, and the annotation class defining plugin properties.
  • A custom plugin type requires a base class extensible by all plugins. This class implements the interface and uses dependency injection for the form_builder service, essential for form construction. The plugin interacts with form classes; the next step is integrating these forms with node displays.

Plugin Manager:

The plugin manager, crucial for discovering and loading plugins, extends Drupal's DefaultPluginManager. Within the module's /src directory, ReusableFormManager.php contains:

<?php namespace Drupal\reusable_forms;

use Drupal\Core\Plugin\DefaultPluginManager;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;

class ReusableFormsManager extends DefaultPluginManager {

  public function __construct(\Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler) {
    parent::__construct('Plugin/ReusableForm', $namespaces, $module_handler, 'Drupal\reusable_forms\ReusableFormPluginInterface', 'Drupal\reusable_forms\Annotation\ReusableForm');
    $this->alterInfo('reusable_forms_info');
    $this->setCacheBackend($cache_backend, 'reusable_forms');
  }
}
Copy after login
Copy after login

This extends DefaultPluginManager, overriding the constructor. Key parameters define:

  • Plugin/ReusableForm: Plugin subdirectory.
  • Drupalreusable_formsReusableFormPluginInterface: Required plugin interface.
  • Drupalreusable_formsAnnotationReusableForm: Annotation class defining plugin properties.

An alter hook (reusable_forms_info) allows modules to modify plugin definitions, and the cache backend is configured.

Plugin Interface:

The interface (ReusableFormPluginInterface.php in /src) defines methods all plugins must implement:

<?php namespace Drupal\reusable_forms;

use Drupal\Core\Plugin\DefaultPluginManager;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;

class ReusableFormsManager extends DefaultPluginManager {

  public function __construct(\Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler) {
    parent::__construct('Plugin/ReusableForm', $namespaces, $module_handler, 'Drupal\reusable_forms\ReusableFormPluginInterface', 'Drupal\reusable_forms\Annotation\ReusableForm');
    $this->alterInfo('reusable_forms_info');
    $this->setCacheBackend($cache_backend, 'reusable_forms');
  }
}
Copy after login
Copy after login

getName() returns the plugin name; buildForm() accepts an entity and returns a render array for a form implementing Drupalreusable_formsFormReusableFormInterface. It extends PluginInspectionInterface and ContainerFactoryPluginInterface for added functionality and dependency injection.

Plugin Annotation:

The annotation class (ReusableForm.php in /src/Annotation) defines plugin properties:

<?php
namespace Drupal\reusable_forms;

use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Component\Plugin\PluginInspectionInterface;

interface ReusableFormPluginInterface extends PluginInspectionInterface, ContainerFactoryPluginInterface {

  public function getName();

  public function buildForm($entity);
}
Copy after login

id, name, and form (the fully qualified form class name) are defined here.

Plugin Base Class:

The plugin base class (ReusableFormPluginBase.php in /src) provides defaults:

<?php
namespace Drupal\reusable_forms\Annotation;

use Drupal\Component\Annotation\Plugin;

/**
 * @Annotation
 */
class ReusableForm extends Plugin {

  public $id;
  public $name;
  public $form;
}
Copy after login

This extends PluginBase, implements ReusableFormPluginInterface, and uses dependency injection for form_builder. getName() and buildForm() are implemented, using the form class specified in the annotation.

Form Interface and Base Class:

A simple form interface (ReusableFormInterface.php in /src/Form) and base class (ReusableFormBase.php in /src/Form) are created for consistency: (These are shown in the original response, and are not repeated here for brevity).

Conclusion (Part 1):

This first part sets up the custom plugin type, preparing it for integration with form classes. Part two will cover displaying these forms with nodes, involving node type configuration and form rendering within content view modes.

The above is the detailed content of Drupal 8 Custom Plugin Types. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles