John
John John has been developing websites and software for over 20 years. Focusing on Drupal over the last 12 years.

Drupal 8: Using Drupal Console to create a custom Views field plugin.

Drupal 8: Using Drupal Console to create a custom Views field plugin.

Drupal Console is a new tool for Drupal 8 which will generate boilerplate code when creating modules, custom entities and much more. It also behaves a little like Drush.

Project homepage

Documentation

Some examples of the boilerplate code that is generated using Drupal Console.

Custom Views Field

I recently wanted to output some information in a View that was formatted to output a table. For one of the columns I wanted to output some simple text depending on data from two other fields. The best way to achieve this was to create my own custom Views field plugin.

Luckily, Drupal Console gives us some very good boilerplate code to get us started.

So, I ran the following command to get Drupal Console to create my plugin code:

drupal generate:plugin:views:field --module="mymodule" --class="MyModuleViewsField" --
title="My module views field" --description="My awesome views field plugin."

You could simplify the previous command to utilise the Drupal Console alias:

drupal gpvf --module="mymodule" --class="MyModuleViewsField" --
title="My module views field" --description="My awesome views field plugin."

So what this does is go off and create the required directories and files that we need.

modules/custom/mymodule/src/Plugin/views/field/MyModuleViewsField.php modules/custom/mymodule/mymodule.views.inc

mymodule.views.inc

You will need to let Views know that you are creating a new field by implementing hook_views_data()

<?php

/**
* Implements hook_views_data().
*/
function mymodule_views_data() {

    $data['views']['table']['group'] = t('Custom Global');
    $data['views']['table']['join'] = [
      // #global is a special flag which allows a table to appear all the time.
      '#global' => [],
    ];


    $data['views']['my_module_views_field'] = [
        'title' => t('My module views field'),
        'help' => t('My awesome views field plugin.'),
        'field' => [
            'id' => 'my_module_views_field',
        ],
    ];

    return $data;
}

src/Plugin/views/field/MyModuleViewsField.php

<?php

namespace Drupal\mymodule\Plugin\views\field;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Component\Utility\Random;
use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\views\ResultRow;

/**
 * A handler to provide a field that is completely custom by the administrator.
 *
 * @ingroup views_field_handlers
 *
 * @ViewsField("my_module_views_field")
 */
class MyModuleViewsField extends FieldPluginBase {

  /**
   * {@inheritdoc}
   */
  public function usesGroupBy() {
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function query() {
    // Do nothing -- to override the parent query.
  }

  /**
   * {@inheritdoc}
   */
  protected function defineOptions() {
    $options = parent::defineOptions();

    $options['hide_alter_empty'] = ['default' => FALSE];
    return $options;
  }

  /**
   * {@inheritdoc}
   */
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    parent::buildOptionsForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function render(ResultRow $values) {
    // Return a random text, here you can include your custom logic.
    // Include any namespace required to call the method required to generate
    // the desired output.
    $random = new Random();
    return $random->name();
  }

}

Most of this code we don’t need to worry about, the main method we need to look at is the render() method.

This is where we can get access to all the values of each row in the view and grab any data we want, to decide what we output in our custom field.

Once you have this in place and cleared the caches drush cr then head over to your view, add a field and search for Global and you should see your newly created field listed.

Views Add Field Modal

Please leave a comment with any feedback or if you feel I have explained something incorrectly.

comments powered by Disqus