In previous articles I have written about injecting context into context aware plugins and creating custom context providers and wanted to complete the series by writing about creating context aware custom plugins.
The context system in Drupal is a powerful way of injecting dynamic data into plugins without writing code to add that data directly to the plugin itself. Instead of adding custom code to find the current user or the node from the route of the page you can inject the context into the plugin using the context system and add code to make use of that data. Although most commonly used in blocks it can be found in a couple of other plugin types in Drupal core, like the condition plugin for example.
In this article I will go through how to create a context aware plugin, including how to create custom plugins and how to allow that plugin to understand the context_definitions annotation. Once the custom plugin is complete we will render it using a Drupal controller action to prove that the context works correctly.
Let’s start by creating a custom plugin, we’ll call this plugin ContextThing and it will be used to print out the context passed to it. The first step in creating custom plugins is to create an Annotation class.
Plugin Annotation Class
Annotations are special kinds of comments that have a number of functions in Drupal, but in this case we are using them to inform Drupal that a particular class is plugin.
As an example of annotations in action we can look at defining custom Blocks. To define a block plugin you would start the class annotation with @Block and then add the fields you need to the annotation definition. This would look something like this.