Drupal 7: Alter filter criteria to "current user" in node views

  • 11 Dic 2013
  • Drupal 7

Days ago I had the need to find the "current user" option within the module "filter criteria" in views 3. I found that when the same filter is used in "context filters" Views, use the wildcard ***CURRENT_USER***, so I decided to use the same wildcard in filter criteria.

Create a module called "views current user" (views_current_user)

If we want to filter the view called "images" the code should be something like this:

function views_current_user_views_query_alter(&$view, &$query) {

  watchdog('gallery', '<pre>' . print_r( $query, true) . '</pre>');

  if ($view->name == "images") {

    $query->where[1]['conditions'][2]['value'] = "***CURRENT_USER***";
    $query->where[1]['conditions'][2]['operator'] = "=";
  }
}

Drupal log

watchdog is my friend. The first thing I do is log the query object so I know the correct "where" entry I have to alter.

watchdog('gallery', '<pre>' . print_r( $query, true) . '</pre>');

Give the user logged

This is the code of /sites/all/modules/views/modules/user.views.inc

/**
 * Allow replacement of current userid so we can cache these queries
 */
function user_views_query_substitutions($view) {
  global $user;
  return array('***CURRENT_USER***' => intval($user->uid));
}

Here is the magic... Wherever you put ***CURRENT_USER*** will be replaced by the logged in user id (uid).

Fine.