Plugins are swappable pieces of code in Drupal 8. To see how different they are from hooks, let’s take an example where we want to create a new field type.
In Drupal 7, this involves:
- Providing information about the field
hook_field_info– describes the field, adds metadata like label, default formatter and widget.
hook_field_schema– resides in the module’s .install file. Specifies how the field data is stored in the database.
hook_field_validate– validates the field content before it is persisted in the database.
hook_field_is_empty– criteria which decides when this field is considered “empty”.
- Describe how the field will be displayed using,
hook_field_formatter_info– metadata about different types of formatters.
hook_field_formatter_view– implementation of the formatters defined above, mostly spits out HTML.
- Define a widget for the field type.
hook_field_widget_info– provides information about widgets. For instance, a calendar would be a widget for a date field.
hook_field_widget_form– implements the widgets.
In Drupal 8, all the 3 steps mentioned above(field info, formatters and widgets) are 3 types of plugins.
- Providing information about the field. This is done by the
FieldTypeplugin which extends
FieldItemBase. The FieldItemBase class has schema, metadata and validation encapsulated which will need to be overriden by the developer.
- Field formatter. Implemented by extending
viewElements()function needs to be overridden to provide a renderable array for a field value. This is similar to the
hook_field_formatter_viewin Drupal 7.
- Widgets are implemented by subclassing
There is many more to creating field types than that, but that’s all you need to know from a plugins perspective.
What did we gain by changing fields from being a hook based system to plugins based? For one, the code became more encapsulated. The definition and implementation is wrapped in one place. Another benefit we reaped by following OO principles is inheritance. Plugins are designed to be extensible. This allows us to subclass similar functionality and achieve one of the most coveted ideals of software engineering, i.e. code reuse.
In the next part, we will look at the concept of plugin discovery and some common plugin types exposed by Drupal 8 core.