Skip to main content
Drupal 8

Main navigation

  • Home
    • Question And Answer
    • NEWS
    • Projects
  • Tutorials - Drupal
    • Android
    • Other
User account menu
  • Log in

Breadcrumb

  1. Home

Custom Views Data handler for a custom Entity on drupal 8

By editor , 11 October, 2016
Question

How to add a custom Views Data handler for a custom Entity on drupal 8 ?

Once created your entity as Basic Entity or Full Entity, you can add a custom views handler.

1. Create  your entity views data extended from Drupal\views\EntityViewsData.

Note : You can also use the default views handler ( *     "views_data" = "Drupal\views\EntityViewsData",) without creating a custom class. But you can't change the views data structure.

Example: /vehicle/src/VehicleViewsData.php

<?php
namespace Drupal\vehicle;
use Drupal\views\EntityViewsData;
/**
 * Provides the views data for the entity.
 */
class VehicleViewsData extends EntityViewsData {
  /**
   * {@inheritdoc}
   */
  public function getViewsData() {
    $data = parent::getViewsData();
    //Go to the following url to get details.
    //https://api.drupal.org/api/drupal/core!modules!views!views.api.php/function/hook_views_data/8.2.x
    return $data;
  }
}

More details about views data :  https://api.drupal.org/api/drupal/core!modules!views!views.api.php/function/hook_views_data/8.2.x

 

2.  Add this Class to the entity. For that, simply add the following line to the Entity handler

 *     "views_data" = "Drupal\vehicle\VehicleViewsData",

Like:

 *   handlers = {
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
 *     "list_builder" = "Drupal\vehicle\Entity\Controller\VehicleListBuilder",
 *     "views_data" = "Drupal\vehicle\VehicleViewsData",
 *     "form" = {
 *       "add" = "Drupal\vehicle\Form\VehicleForm",
 *       "edit" = "Drupal\vehicle\Form\VehicleForm",
 *       "delete" = "Drupal\vehicle\Form\VehicleDeleteForm",
 *     },
 *     "access" = "Drupal\vehicle\VehicleAccessControlHandler",
 *   },

3. Now, clear all cache and you can create views with your entity.

 

File : Example with Basic Entity (Full example already has this views)

File
vehicle_basic_wviews.zip (2.04 KB)

Tags

  • Drupal 8
  • Code
  • Entity
  • Views
Create a custom Content Entity on drupal 8 (Full)
Views with custom Tables - hook_views_data
Create a custom Content Entity on drupal 8 (Basic)

Comments

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

Links

  • Drupal.org
  • Drupal core release cycle
  • Drupal events with ease
  • Unit test with Drupal using PHPUnit (Drupal 10)
  • Tokens for file upload url
  • Tips for Docker
  • CKEditor inline image files usage for custom forms.
  • Install Docker on Linux Mint
  • Install PHP 8.1
  • Drupal Security Best Practices
  • Order and sort items with tabledrag
  • Add a custom service YAML container
  • Apply a patch with composer