Я пытаюсь взять результаты представления - использование функции views_get_view_result()
- и сортируют массив способом, я не мог сделать из интерфейса Views.Пока все хорошо. У меня есть переменная $rows со всем материалом, в котором я нуждаюсь.
Теперь... Как я откладываю его?:) Прежде чем мне был нужен этот вид, я использовал views_embed_view()
, но я не могу больше делать этого.
Благодарный за любую справку на этом, чувствует, что я так близко к взламыванию ее!
$important_var = important_function();
$result = views_get_view_result($view, $display, $args);
$result = sorting_function($result, $important_var);
//TODO: Put the result back into the view
Модуль представлений предоставляет некоторые хуки для «внешних» манипуляций, как и ядро Drupal.
Вы можете реализовать hook_views_pre_render (& $ view)
в пользовательском модуле и управлять массивом результатов, доступным в $ view-> result
:
/**
* Implementation of hook_views_pre_render()
*
* @param view $view
*/
function YourModuleName_views_pre_render(&$view) {
// Check if this is the view and display you want to manipulate
// NOTE: Adjust/Remove the display check, if you want to manipulate some/all displays of the view
if ('YourViewName' == $view->name && 'YourDisplayName' == $view->current_display) {
// EXAMPLE: Just reverse result order
// TODO: Replace with your desired (re)ordering logic
$view->result = array_reverse($view->result);
}
}
Хук вызывается в в середине процесса генерации представления, после того, как все данные результатов были собраны, но до того, как будет отрисован фактический вывод, поэтому изменения в массиве результатов будут отражены в окончательном выводе представления.
РЕДАКТИРОВАТЬ: В качестве альтернативы вы можете обработать представление «вручную», скопировав поведение функции views_get_view_result ()
, но вместо того, чтобы возвращать результат, вы манипулируете им и продолжаете рендеринг вид:
function yourModule_get_custom_sorted_view($display_id = NULL) {
// As the custom sorting probably only works for a specific view,
// we 'demote' the former $name function parameter of 'views_get_view_result()'
// and set it within the function:
$name = 'yourViewName';
// Prepare a default output in case the view definition can not be found
// TODO: Decide what to return in that case (using empty string for now)
$output = '';
// Then we create the result just as 'views_get_view_result()' would do it:
$args = func_get_args();
if (count($args)) {
array_shift($args); // remove $display_id
}
$view = views_get_view($name);
if (is_object($view)) {
if (is_array($args)) {
$view->set_arguments($args);
}
if (is_string($display_id)) {
$view->set_display($display_id);
}
else {
$view->init_display();
}
$view->pre_execute();
$view->execute();
// 'views_get_view_result()' would just return $view->result here,
// but we need to go on, reordering the result:
$important_var = important_function();
$view->result = sorting_function($result, $important_var);
// Now we continue the view processing and generate the rendered output
// NOTE: $view->render will call $view->execute again,
// but the execute method will detect that it ran already and not redo it.
$output = $view->render();
// Clean up after processing
$view->post_execute();
}
return $output;
}
Примечание: Это много дублирования кода и, следовательно, подвержено ошибкам - я не рекомендую это и предпочитаю использовать описанную выше реализацию ловушки, пытаясь найти способ получить доступ к вашему '$ important_var 'изнутри.
В зависимости от вашей логики сортировки вы можете попробовать использовать hook_views_query_alter () для реализации сортировки непосредственно в запросе.
Это может быть немного сложно, вы можете ознакомиться с объектом views_query.
Вот реальный пример, когда я применил правило объединения на основе контекста страницы, а затем дополнительно добавил правила сортировки.
/**
* Implementation of hook_views_query_alter().
*/
function yourmodule_views_query_alter(&$view, &$query) {
if ($view->name == 'view_projects' && $view->current_display == 'panel_pane_4') {
if (arg(0) == 'node' && is_numeric(arg(1))) {
$node = node_load(arg(1));
if ($client_nid = $node->field_ref_client[0]['nid']) {
$query->table_queue['node_node_data_field_ref_client']['join']->extra = "field_ref_client_nid = " . $client_nid;
$query->add_orderby('node', NULL, 'DESC', 'node_node_data_field_ref_client_nid');
$query->add_orderby('node', 'created', 'DESC');
}
}
}
}
См .: http://drupalcontrib.org/api/function/hook_views_query_alter/6