Module Development

Define a Custom Views Pseudo Field Plugin for Drupal 8, 9, and 10

By default the Views module can display data contained in any field attached to an entity that is exposed in Views, and the content of any database column exposed to Views via an implementation of hook_views_data(). It's also possible to create pseudo fields. These appear in the Views UI like any other field, but don't map directly to the data stored in a database column and instead allow the data to be preprocessed. This could be performing a calculation, combining multiple fields into one, and much more.

A common example in core is the fields that allow you to perform edit or delete operations on a node. These don't correspond to a specific database column. And they can't be hard-coded because they require dynamic content specific to the node in question. Instead, they are the result of taking the entity ID and combining it with knowledge about the appropriate route for someone to edit the entity and outputting that as a link.

Another example: Imagine a cooking website where you collect cook time and preparation time (prep time) for recipes and want to also display the full time to prepare. In this case cook time and prep time could be fields on the recipe content type and total time could be handled as a calculated output of both fields, added together and converted into hours and minutes. To achieve this, you can create a custom Views pseudo field and specify the calculation and processing logic in the render function.

In this tutorial we'll:

  • Learn how to define a custom Views field plugin for a pseudo field
  • Attach the created field to node entities, and expose it to display in a view

By the end of this tutorial you should know how to define a Views pseudo field plugin, attach it to the node entity type via hook_views_data_alter(), and display it in a view.