Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
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.

Comments

Submitted by Shiq (not verified) on Thu, 11/26/2020 - 18:32 Permalink

Hi, I just wanted to thank you for providing such good code. Works great!
Add new comment

Restricted HTML

Search

Page Facebook

Become a patron

If you need some help or you search a Drupal freelancer don't hesitate to contact us.

 

Contact Us

All the content is FREE but I still need your help

 

Become a patreon