Skip to main content
D

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:

Tree

Create files

Lets follow these steps:

  1. Create a directory field_token under web/modules/custom
  2. Create info file field_token.info.yml 
  3. Create a path src/Plugin/views/field and create a file FieldTokenPlugin.php inside it
  4. This is a class file which extends FieldPluginBase, we need to provide the plugin id in annotation @ViewsField above class name.
  5. 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

  1. At root directory create file field_token.views.inc
  2. 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.

  1. Goto structure/views and create a view lets name it Try Field Token Plugin
  2. Create page with content of type Basic page as shown below
  3. Create view
  4. Now add the field Field Token Plugin
  5. View
  6. 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/