rupal backend development has great deal in core Views. There are many important plugins that we can develop to improve our experience of Drupal Development. Once you learn how the different parts of views work, and then learn how can we improve and speed up Drupal development using different kinds of plugins.
In this article we would develop a view field plugin. The task of this view would be to find certain words in the text and make it bold. We can extend this feature to do a variety of tasks. For example remove sentences containing certain words, or replace a token by some URL etc.
Directory structure
We will create the basic file structure as follow:
Create files
Lets follow these steps:
- Create a directory field_token under web/modules/custom
- Create info file field_token.info.yml
- Create a path src/Plugin/views/field and create a file FieldTokenPlugin.php inside it
- This is a class file which extends FieldPluginBase, we need to provide the plugin id in annotation @ViewsField above class name.
- Next write the code logic in the render method, the render method gets each row from the view query as a parameter.
Implement hook
We need to define a hook to let Drupal know about our new plugin. We will create a file field_token.views.inc
- At root directory create file field_token.views.inc
- Inside this file implement hook: hook_views_data_alter(), we will replace the hook part by field_token
Use Plugin
Now its time to clear cache and enable the plugin.
Try the new plugin
Now its time to prove the proof of concept. First we need to create a page containing our awesome token [search] or [search-engine] and after that we will create a view which uses our best plugin we just developed.
- Goto structure/views and create a view lets name it Try Field Token Plugin
- Create page with content of type Basic page as shown below
- Now add the field Field Token Plugin
- And browse the page by clicking View
Download
To download the source code from local server:
ssh://ali@g10:2222/home/ali/repos/modules/field_token/