The view is a powerful module for querying and displaying information and can save you a lot of hassle when dealing with the custom data produced by Drupal modules. Drupal views make it easy to query/display data, including custom table data. In this article, you are going to learn how to expose the table created by your Drupal module to Views.
The focus of this tutorial will be on data that is not abstracted as Drupal entities but simply stored in a table.
To help Drupal views understand the exposure of modules and custom table data, we use hook_views_data().
Drupal 8 and Drupal 9 support Views Custom Table. And alternatively, we can use hook_views_data to achieve our goal. But the Views custom table already uses hook_view_data to add custom tables in views. So, it will extend the functionality.
Let's start with the Views Custom table.
The view custom table module provides the functionality to integrate your custom table data to view and access all its columns in the custom views. This module offers you the following functionalities.
Here's a demo using a user entity with a custom table.
Step 1
Login with administrator -> Navigate to people -> Add some people data.
Create a Custom table
Note: The schema definition is already in the module. Therefore, let's not repeat here again.
Here, I've modified the table structure. I will give you a short MySQL command & MYSQL definition to generate a couple of dummy records to play with it. Hopefully, this command is informative enough to describe the table structure as well:
MYSQL definition
CREATE TABLE `user__ct` ( |
ALTER TABLE `user__ct` |
MYSQL Command
INSERT INTO `user__ct` (`bundle`, `entity_id`, `uid`, `ct_target_id`) VALUES |
Go to Home » Administration » Structure » Views » View Custom Table
Step 4
Add your custom table to the system using the "Add Custom Table" link.
Add Relationships with Drupal entities if any, otherwise, leave none.
The custom demo table has a user uid relationship. Therefore, I added a relation to the column entity_id and uid table. If you do not want to give a specific relationship, then don’t keep any.
Step 6
Clear the Drupal cache
Step 7
Add a new view. You will see your custom table name in the "Show" drop-down field.
Here we are exploring two demos: