1

I've got a problem with hook_views_query_alter(). I want to override the view's query with a rather complex one. In the first step, I placed the hook in my views.inc and tested it. The hook is called. But none of my tests to alter the query worked.

function glass_lagermanagement_views_query_alter(&$view, &$query) {
  if ($view->name == 'lagerbestand') {
    $query = db_select('materials');
    $query->condition('materials.ID', 1, '==');
  }
}

To test the function, I want to show only one entry which has got the ID "1", but nothing happens at all in the view. What am I doing wrong?

I'm using Drupal 7 here. It is an old project I need to update.

1

I got it. I used this code to alter the query and it worked.

$query->where[1]['conditions'][0] = array('field'=>"materials.ID","value"=>'1',"operator"=>"LIKE");
0

Based on the documentation of hook_views_query_alter you can change the condition by using the following code :

foreach ($query->where as &$condition_group) {
  foreach ($condition_group['conditions'] as &$condition) {
    // If this is the part of the query filtering on title, change the
    // condition to filter on node ID.
    if ($condition['field'] == 'node.title') {
      $condition = array(
        'field' => 'node.nid',
        'value' => $view->exposed_raw_input['title'],
        'operator' => '=',
      );
    }
  }

Which means that in your case :

//foreach 
if ($condition['field'] == 'materials.ID') {
  $condition = array(
    'field' => 'materials.ID',
    'value' => 1,
    'operator' => '=',
  );
}

You can also check this post for another way.

  • Thank you for your answer. Sadly it still does not work. I tried other fields and values, I deactivated and activated my module, cleared the cache several times but still the view does not change at all. The changes of the query are not called, the query still looks the same. I tried $query->orderby[0]['direction'] = "DESC"; and that worked. But the condition-changes wont. May there be a problem because the fields are from the data tables module? My code now looks like this: if($view->name == 'lagerbestand'){ $query->orderby[0]['direction'] = "DESC"; //works foreach ($query->where as &$conditi – Sovori Jun 24 '17 at 5:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.