Skip to main content
Category:

How to modify an existing views join using hook_views_query_alter in Drupal, Alter the query before it is executed.

This will let you alter the query before you execute the query so you have a chance to request a different set of data than originally configured within the views.

First, check the tables that you have in your query, it could be a table alias or a table name. The following code will show you the list of tables.

$query->tables;

Then you know what table you need to alter so do the following

/**
 * Implements hook_views_query_alter().
 */
function MODULE_views_query_alter(ViewExecutable $view, QueryPluginBase $query){

  if ($view->storage->get('id') === 'VIEWNAME' && $view->current_display === 'DISPLAY') {
    $query->addTag('debug');

    $table = $query->getTableInfo('MY TABLE NAME');
    $table['join']->extra = [];
    // Example
    $table = $query->getTableInfo('vehicle__field_make_model_value_0');
    $table['join']->extra[] = [
      'field' => 'title',
      'value' => 'management',
      'operator' => '!='
    ];
  }
}

 

Example 2 Add condition in query alter views


function Module_views_query_alter(ViewExecutable $view, QueryPluginBase $query)
{
    switch ($view->storage->id()) {
        case 'Page':
            if ($view->current_display == 'block_1') {
                $node = \Drupal::routeMatch()->getParameter('node');
                $categoryId = $node->get('field_category')->target_id;
                $query->addField('taxonomy_term_field_data', 'tid');
                $query->addWhere('conditions', 'taxonomy_term_field_data.tid', $categoryId, '!=');
            }
            break;

    }
}

Api: hook_views_query_alter.

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook