Views query substitutions in Drupal 6

Submitted by charles on

Was adapting some views handlers that were used in Open Atrium, and came across a number of places where I saw some strange constants with three stars either side of them, like: ***ATRIUM_ACTIVITY_TIMESTAMP***

/**
* Query. This relies on the hijacking of the Views execution process in
* atrium_views_query_alter().
*/
function query() {
parent::query();
if (!isset($this->view->atrium_activity)) {
$this->view->atrium_activity = TRUE;
$node = $this->query->ensure_table('node');
$comments = $this->query->ensure_table('comments');
$horizon = $this->options['time_horizon'] * 24 * 60 * 60;
$this->query->add_orderby(NULL, "***ATRIUM_ACTIVITY_TIMESTAMP***", 'DESC', 'atrium_activity_sort');
$this->query->add_where(NULL, "***ATRIUM_ACTIVITY_TIMESTAMP*** > (***CURRENT_TIME*** - $horizon)");
}
}

From what I can gather, this is a convention for using placeholders in views where we define our own queries in code like in custom handlers, and works in cached queries.

So when the views query is run, our placeholder is replaced with an actual value if we've defined this replacement using hook_views_query_substitutions(). If we haven't then we need to manually make the replacement.

An example using the hook:

/**
* Substitute current time; this works with cached queries.
*/
function views_views_query_substitutions($view) {
global $language;
return array(
'***CURRENT_VERSION***' => VERSION,
'***CURRENT_TIME***' => time(),
'***CURRENT_LANGUAGE***' => $language->language,
'***DEFAULT_LANGUAGE***' => language_default('language'),
'***NO_LANGUAGE***' => '',
);
}

If we haven't defined it using this hook, we can just alter the query ourselves using something like:

$query = strtr($query, array('***ATRIUM_ACTIVITY_TIMESTAMP***' => 'comments.timestamp'));

Some more examples of how this can be used:

/**
* Implementation of hook_views_query_substitutions().
*/
function node_views_query_substitutions() {
return array(
'***ADMINISTER_NODES***' => intval(user_access('administer nodes')),
);
}

 

/**
* 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));
}