视图模块 provides some hooks 用于“外部”操作,就像 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' 来自其中。