Skip to main content
Image
EstadΓ­sticas

Create custom field in a view

In many specific cases, the project we work on may require us to fulfill a specific use case, which a Drupal 8 view is not capable of providing through the GUI. But as we already know, Drupal 8 is flexible and has a powerful API in views that allows us to customize them and adapt them to our needs. Today I am going to explain how to create custom fields in Drupal 8 views .

Folder structure

First and foremost, we must have or create a custom module. I have never explained nor do I plan to explain how to create a custom module in Drupal 8, because I think there is enough documentation about it on the internet. Even so, there are tools like Drupal Console, which I explain how to download and install in my post , which allows us to easily create a custom module from the console through several sequential questions. We can also do it manually, creating the necessary folder structure.

Our folder structure for the β€œmycustom_module” module looks like this:

β”œβ”€β”€ mycustom_module
    β”œβ”€β”€ mycustom_module.info.yml
    β”œβ”€β”€ mycustom_module.views.inc
    β”œβ”€β”€ src
    β”‚   └── Plugin
    β”‚       β”œβ”€β”€ views
    β”‚       β”‚   └── field
    β”‚       β”‚       └── ShowRoles.php

We will briefly explain what each file does:

  • mycustom_module.info.yml: collects information about the custom module that we have created.
  • mycustom_module.views.inc: is the file used in Drupal 8 to launch hooks such as hook_views_data_alter or hook_views_data. In Drupal 7 it was done directly in the .module. You can find info here about this change.
  • ShowRoles.php: class that contains the logic that we want to apply to the field that will be shown in the view. Inherits from FieldPluginBase.

Creating the field

Once we have our folder structure correct, we will focus on ShowRoles.php first and mycustom_module.views.inc second.

This is how our ShowRoles.php would look.

<?php
namespace Drupal\ocai_module\Plugin\views\field;

use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\views\ResultRow;
use Drupal\user\Entity\User;

/**
 * Field handler to show user's roles.
 *
 * @ingroup views_field_handlers
 *
 * @ViewsField("show_roles")
 */
class ShowRoles extends FieldPluginBase {

  /**
   * @{inheritdoc}
   */
  public function query() {
  }

  /**
   * @{inheritdoc}
   */
  public function render(ResultRow $values) {

    $user = User::load(\Drupal::currentUser()->id());
    $user_roles = $user->getRoles();
    $output['#markup'] = 'Hey ' . $user->getUsername() . ' your roles are: <br>'
    . implode(', ', $user_roles);

    return $output;
  }
}

Our field is very simple; The only thing it will do is show the roles of the current logged in user (with a session started) in a route that we will configure later from the view interface. The important thing about this class is that it must inherit from FieldPluginBase, therefore the render() and query() methods will be overridden. Be very careful with the annotation @ViewsField(β€œshow_roles”), which will be where we configure the ID of our custom field.

This is how our mycustom_module.views.inc would look.

<?php  
  
/**  
 * Implements hook_views_data_alter(). {  
  
  $data['node']['show_roles'] = [  
  'title' => t('Show roles to user'),  
  'field' => [  
  'title' => t('Show roles to user'),  
  'help' => t('Show roles to current user'),  
  'id' => 'show_roles',  
  ],  
  ];  
}

Here it is important that the ID and the one we put in ShowRoles.php match correctly. Finally, we will make sure that the files have the appropriate permissions. Next we execute the drush cr command to clear caches.

Setting the view in the interface

Now we will work on creating the view from the Drupal administration interface. When we search in the β€œFields” of the view, if we have done everything correctly our custom field will appear in the list of available fields.

Once we find it, we will apply it to the view. We will configure the path '/view-test', for example, to display the custom field there. The final result will be the following:

Join the Drupal Sapiens Community

Save content that interests you, connect with others in the community, contribute to win prizes and much more.

Login or create an account here

Latest posts

Featured

Last news