prethiee

Commonly Used Hooks and Query Alterations in Drupal Views

Drupal's Views module is a powerful tool that allows site builders to create dynamic lists and displays of content without writing custom code. However, developers often need to extend or modify Views to meet specific requirements. This is where hooks and query alterations come into play. In this blog, we will explore some commonly used hooks and how to alter queries in Drupal Views.
 
Commonly Used Hooks in Drupal Views
1. `hook_views_query_alter()`
 
This hook allows you to modify the SQL query that Views generates. It is commonly used to add custom conditions, joins, or alter the query in other ways before it is executed.
Example: Adding a Custom Condition to a View Query
function custom_module_views_query_alter(&$view, &$query) {
if ($view->id() == 'my_custom_view') {
  // Add a custom condition to the query.
  $query->addWhere(0, 'field_custom_column', 'value_to_match', '=');
 }
}
In this example, the hook checks if the view ID is `my_custom_view` and adds a condition to filter results based on a custom field.
2. `hook_views_pre_render()`
This hook is invoked just before the view is rendered. It's useful for making last-minute modifications to the result set or the view's structure.
Example: Modifying Results Before Render
function custom_module_views_pre_render(&$view) {
if ($view->id() == 'my_custom_view') {
    // Loop through the result set and modify it.
    foreach ($view->result as &$row) {
      $row->_entity->field_custom_field->value = 'Modified Value';
   }
  }
}
Here, the hook checks the view ID and modifies the value of a custom field in each row before the view is rendered.
3. `hook_views_post_build()`
This hook is invoked after the view has been built but before it is rendered. It is useful for making changes to the view’s structure, such as adding or modifying exposed filters.
Example: Adding an Exposed Filter Programmatically
function custom_module_views_post_build(&$view) {
  if ($view->id() == 'my_custom_view') {
  // Add a new exposed filter.
  $view->display_handler->display['display_options']['filters']['status'] = [
   'id' => 'status',
   'table' => 'node_field_data',
   'field' => 'status',
   'value' => 1,
   'exposed' => TRUE,
   ];
  }
}
In this example, an exposed filter is added programmatically to the view.
 
4. `hook_views_data_alter()`
This hook allows you to modify the Views data definition, which controls how fields, filters, and relationships are exposed to Views.
Example: Adding a Custom Relationship
function custom_module_views_data_alter(array &$data) {
  // Add a custom relationship to the node table.
  $data['node']['my_custom_relationship'] = [
    'title' => t('Custom Relationship'),
    'help' => t('A custom relationship added by custom module.'),
    'relationship' => [
    'base' => 'my_custom_table',
    'base field' => 'nid',
    'relationship field' => 'nid',
    'label' => t('Custom Relationship'),
   ],
 ];
}
This example demonstrates adding a subquery to filter nodes based on a condition in a custom table.
 
Altering the Query with Views Plugins
Sometimes, you may need more granular control over the query, which can be achieved by creating a custom Views plugin. This approach is more complex but offers full control over how Views interacts with the database.
Example: Creating a Custom Query Plugin
1. Create the Plugin:
Define your custom query plugin by extending `ViewsPluginQueryDefault`.
namespace Drupal\custom_module\Plugin\views\query;
use Drupal\views\Plugin\views\query\Sql;
/
* Custom Query Plugin.
*
* @ViewsQuery(
* id = "custom_query",
* title = @Translation("Custom Query"),
* help = @Translation("Custom query for specific use case.")
* )
*/
class CustomQuery extends Sql {
// Override necessary methods to customize the query.
}
2. Use the Plugin in a View:
- When defining a view, select your custom query plugin to take full control over the query's behaviour.

Conclusion
Drupal’s Views module, combined with hooks and query alterations, provides developers with the flexibility to customize data displays to meet complex business requirements. By mastering commonly used hooks like `hook_views_query_alter()`, `hook_views_pre_render()`, and `hook_views_data_alter()`, along with understanding how to alter queries, you can unlock the full potential of Views in your Drupal projects.