6

Let's say that I want to replace the block_content_type plugin of the core block_content module to ad some features while not having to rewrite a whole module to achieve this.

It is very easy to replace a service by providing your own service definition with the same key as the to-be-replaced service. How do I replace a plugin with another one?

0

1 Answer 1

13

To answer the general question how do you do that with plugins: Each plugin type is managed by a plugin manager. You can list all plugin manager classes with this console command:

drupal debug:plugin

Most plugin managers provide an alter hook to change the plugin definitions. Look in the plugin manager class method __construct for a line with $this->alterInfo():

public function __construct(...) {
  ...
  $this->alterInfo('example_plugin_info');

In this alter hook you can replace the class of plugins managed by this plugin manager:

function mymodule_example_plugin_info_alter(array &$info) {
  if (isset($info['foo_plugin'])) {
    $info['foo_plugin']['class'] = '\Drupal\mymodule\Plugin\ExamplePlugin\MyCustomFooPlugin';
  }
}

You can check the result by executing the same console command, now providing the plugin type as parameter, to list the plugins of this type and their classes:

drupal debug:plugin example_plugin

Entity type classes

About your specific question, the plugin manager for entities is EntityTypeManager (not listed by the console command because it doesn't use the standard service name scheme). It provides an alter hook to alter entity types as well, so if you are referring to the bundle entity type class of Block Content, then you can change it here:

/**
 * Implements hook_entity_type_alter().
 */
function mymodule_entity_type_alter(array &$entity_types) {
  $entity_types['block_content_type']->setClass('...');
}

Using Drush and Devel instead of Drupal Console to debug plugins

Devel adds some useful commands to Drush, one of them is to debug services, which you can filter to list only plugin managers:

drush devel:services plugin.manager.

After you've found the service ID of the plugin manager you can list the plugins discovered by this plugin manager:

\Drupal::service('plugin.manager.example')->getDefinitions();

Run this command from a drush php shell to get a nice output.

For the plugin manager class name look up the service ID in Devel UI (/devel/container/service).

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.