Custom Views Data handler for a custom Entity on drupal 8

Submitted by editor on Tue, 10/11/2016 - 10:13

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

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.
    return $data;

More details about views data :!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",


 *   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)

Add new comment

This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
Enter the characters shown in the image.