0

I want to create a views field plugin. At the moment, I just want to display "Hello world".

I have a custom module "lazy_admin".

This is lazy_admin.info.yml

name: 'lazy_admin'
type: module
description: 'Misc code'
package: Custom
core_version_requirement: ^10
dependencies:
  - drupal:views

This is my views plugin class OpenTickets.php (web/modules/custom/lazy_admin/src/Plugin/views/field/OpenTickets.php)

<?php

namespace Drupal\lazy_admin\Plugin\views\field;

use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\views\ResultRow;

/**
 * @ViewsField("open_tickets")
 */
class OpenTickets extends FieldPluginBase {

  /**
   * Defines how the field is displayed.
   *
   * @param ResultRow $values
   *
   * @return mixed|string
   */
  public function render(ResultRow $values) {
    return $this->t('Hello world');
  }
}

When I enable the module and clear the cache, I expect to be able to select the plugin in the views UI here (I'm using gin admin theme):

Image of views UI

But I cannot find the new field anywhere.

I'm probably missing something obvious, or fundamentally misunderstanding something.

I'm using Drupal 10.2 & PHP 8.2.

2
  • 1
    It's a bit more complicated than that - so far you've created a field handler, not a field. Next step is to assign that handler to one or more fields; exactly how you do that depends on the desired outcome and what the data relates to. What is "open tickets" at its core? Does it represent a field on a content type? Or is it "virtual", e.g. a bundling of data from a few different fields? Or is to more higher-level than that; generic to any entity type, or maybe just a single global value without context?
    – Clive
    Commented May 28 at 12:40
  • Thanks for your comment. It cleared a lot of things up. It seems there was something fundamental I was missing (what you said).
    – Hodgekins
    Commented May 28 at 14:24

1 Answer 1

1

You have to add the field to views data:

/**
 * Implements hook_views_data_alter().
 */
function mymodule_views_data_alter(&$data) {
  $data['views']['open_tickets'] = [
    'title' => t('Open Tickets'),
    'help' => t('Display open tickets.'),
    'field' => [
      'id' => 'open_tickets',
    ],
  ];
}

Use $data['views'] to add a global field. Replace 'views' with the entity type ID if you want to add the field to a specific entity.

1
  • Thank you! This is working as expected now. I also had to override query() in my class with an empty method.
    – Hodgekins
    Commented May 28 at 14:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.