Drupal - How can I let a plugin depend on another module?

Yes, this is possible.

You may declare a dependency on a module by using the "provider" key in the annotation. For your example, this would look like:

/**
 * @FieldWidget(
 *   id = "my_daterange",
 *   label = @Translation("Date and time range + All day"),
 *   field_types = {
 *     "daterange"
 *   },
 *   provider = "date_all_day"
 * )
 */
class MyPlugin {...}

Note that you can only list ONE provider, but of course that provider module can depend on other modules ...

This is a feature added to the DefaultPluginManager in order to allow plugins to declare a dependency on one (and only one) module. This only works for plugins that use a plugin manager derived from DefaultPluginManager.

Specifically, @FieldWidget plugins are managed by the WidgetPluginManager, which DOES subclass DefaultPluginManager, so this will work. (Most, if not all, core plugin managers subclass DefaultPluginManager.)


First, it's probably preferable to use the provider option if you can.

However, Field widgets and formatters also make use of an isApplicable() method. You can use this for any additional logic to determine whether your widget should be available for a field, a field in the subset of fields defined in your annotation.

You can use this method to limit the widget to just a datetime field with a particular machine name, or only datetime fields on nodes, etc.

You can also use it for your case, to check if other modules are enabled.

Tags:

Plugins

8