How to alter view query in Drupal 8?


by lizzie , in category: PHP Frameworks , 8 months ago

How to alter view query in Drupal 8?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by arnoldo.moen , 3 months ago


To alter the query for a view in Drupal 8, you can use one of two approaches:

  1. Use hook_views_query_alter: This hook allows you to alter the query that is used by a view before it is executed. You can use this hook to add additional conditions to the query, join additional tables, or modify the fields being selected. To use this hook, you will need to implement it in a custom module.

Here is an example of how to use hook_views_query_alter to add a condition to a view's query:

function mymodule_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  // Check if the view is the one you want to alter.
  if ($view->id() == 'my_view') {
    // Add a condition to the view's query.
    $query->condition('table_name.field_name', 'value', '=');

  1. Use the views UI: You can also alter the query for a view by modifying the view through the web interface. To do this, go to the "Advanced" section of the view's edit page and click on the "Query Settings" fieldset. From there, you can add additional filters, relationships, and fields to the view.

Keep in mind that the changes you make through the web interface will not be permanent, as they will be lost if the view is exported and reimported. To make your changes permanent, you will need to use one of the available approaches for exporting and importing views in Drupal 8, such as the views_ui module or the configuration management system.