How can I change the sorting of a view using hook_views_pre_view ()?
I have the following:
function view_sorter_views_pre_view(&$view) { // don't need $items
if ($view->name == 'MOST_RECENT') {
$insert = array();
$insert[order] = 'DESC'; //SORT ORDER
$insert[id] = 'title';
$insert[table] = 'node';
$insert[field] = 'title';
$insert[override] = array();
$insert[override][button] = 'Override';
$insert[relationship] = 'none';
unset ($view->display['default']->display_options['sorts']['title']);
$view->display['default']->display_options['sorts']['title'] = $insert;
}
}
Basically, I just change the sort order ... but that doesn't appear in the view when I open it. Any idea why?
+2
a source to share
1 answer
I believe what you want
/**
* Implementation of hook_views_pre_view().
*/
function view_sorter_views_pre_view(&$view) {
if ($view->name == 'MOST_RECENT') {
$view->display['default']->handler->options['sorts']['title']['order'] = 'DESC';
}
}
Views use a handler object to build the request instead of display_options. The display_options contain all the options for each display type that contains the view (e.g. default, page_1, block_1, etc.). The handler object contains parameters that will be used to actually create the current display.
Note. I simplified the code to change the sort order. The rest of your code should work, just change the last two lines to
unset($view->display['default']->handler->options['sorts']['title']);
$view->display['default']->handler->options['sorts']['title'] = $insert;
+2
a source to share