Altering Views data

We saw how we can expose to Views our own data that is totally custom. However, we can also alter existing data definitions provided by Drupal core or other modules by implementing hook_views_data_alter(). The $data parameter passed by reference will contain everything that has been defined and can be changed as needed.

Moreover, we can also use this implementation to create some new Views fields or filters on other tables that do not "belong" to us. This is actually more common than exposing totally custom tables or other kinds of resources. For example, we may want to create a new Views field that shows something related to the Node in the results. So, let's look at an example.

Do you remember in Chapter 6, Data Modeling and Storage, we saw how to create a pseudo field, which outputs a disclaimer message at the bottom of each Node? If our View is configured to render Node entities, that will work. However, if it's using fields, it cannot do that. So, let's see how we could expose this message also as a Views field. We won't include this in the final code, but let's just see how we could get it done if we wanted to.

First, we'd need to implement hook_views_data_alter() and define a new field on the Node entity type data table:

/** 
 * Implements hook_views_data_alter(). 
 */ 
function module_name_views_data_alter(&$data) { 
  $data['node_field_data']['disclaimer'] = [ 
    'title' => t('Disclaimer'), 
    'help' => t('Shows a disclaimer message'), 
    'field' => [ 
      'id' => 'custom', 
    ], 
  ]; 
}  

In this example, we are adding our new Views field onto the Node data table (node_field_data). But then, we have a choice as to what plugin to use to render our message. We can, of course, create one ourselves (as we will do in the next section). This is actually very simple, especially since it doesn't even need to use any of the information from the resulting Nodes. However, if that's the case, we might as well use the existing Custom plugin, which has two main advantages. For one, we don't have to write any more code. Second, it allows the site builder to specify (and modify as needed) the disclaimer message through the UI. Because basically, this plugin exposes a configuration form that we can use to add the text we want displayed for each row:

Of course, there are some drawbacks to this approach as well. If we wanted to ensure consistency between the message here and the one we used in the pseudo field, we would probably want to write our own plugin and get the message from this unique place. The same applies if we wanted the message to be strictly in code, especially if we needed some sort of data from the Node in the View results. So, the choice depends on the actual use case, but it's good to look into the existing Views plugins and see what already exists before creating your own.