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