Skip to content

Instantly share code, notes, and snippets.

@martin-klima
Last active April 27, 2017 16:13
Show Gist options
  • Save martin-klima/c0a7683796008de3db63392cc7a7d40f to your computer and use it in GitHub Desktop.
Save martin-klima/c0a7683796008de3db63392cc7a7d40f to your computer and use it in GitHub Desktop.
Drupal 7: Views query alter: Display something defined by list with the same sorting order
<?php
/**
* Inject Views filter and sorting.
* We need display something defined (nids) with the same sorting order.
*
* The product list view display contains dummy filter, which is overridden
* in this function.
*
* Implements hook_views_query_alter().
*
* @param $view
* @param $query
*/
function module_views_query_alter(&$view, &$query) {
if ($view->current_display == 'your_display_name') {
// Defined nids in defined order.
// Get this array from function or contextual filter or whatever you need.
// $nids_array = example_get_some_nids();
// $nids_array = array(12, 10, 11, 5, 16, 1);
if ($nids_array) {
// Override dummy view filter and fill it with nids.
$view->query->where[1]['conditions'][0]['value'] = array();
$view->query->where[1]['conditions'][0]['operator'] = 'IN';
foreach ($nids_array as $nid) {
$view->query->where[1]['conditions'][0]['value'][] = $nid;
}
// Fill in sorting query.
$nids_order = implode(',', $nids_array);
$view->query->orderby[0]['field'] = "FIELD(nid, $nids_order)";
$view->query->orderby[0]['direction'] = "ASC";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment