Module Development

Expose a Custom Database Table to Views for Drupal 8, 9, 10, and 11

Any Drupal module that provides custom database tables should implement hook_views_data() to describe the schema of those tables to Views. This hook is used to provide information to Views about the fields in a table, their human-readable names, and the types of data (string, integer, date, etc.) stored in each column. You can also tell Views how it should handle sorting, filtering, and formatting the data. Implementations of hook_views_data() can also be used to describe relationships between tables.

If you're creating a module that implements hook_schema() and adds new tables to the database it's a good idea to also add support for Views. Among other things, it'll allow administrators to create any user-facing displays of data from your table using Views. Then, they can be edited without having to write code. Once you've described your table to Views via hook_views_data() Views will be able to provide a way for administrators to construct queries against your data via the UI.

In this tutorial we'll:

  • Use hook_views_data() to expose a custom table defined in a Drupal module to Views.
  • Learn how to describe different types of data to Views.
  • Demonstrate the relationship between hook_views_data() and what a site administrator has access to in the Views UI.

By the end of this tutorial you should know how to describe custom database tables and their fields to the Views module.