Drupal → Хуки Views
Краткое описание хуков Views, вызывающихся в процессе генерации представления:
hook_views_pre_view(&$view, &$display_id, &$args)
Позволяет изменять представление на самой ранней стадии выполнения, до инициализации дисплеев, генерации и выполнения sql запроса.
function hook_views_pre_view(&$view, &$display_id, &$args) { // Change the display if the acting user has 'administer site configuration' // permission, to display something radically different. // (Note that this is not necessarily the best way to solve that task. Feel // free to contribute another example!) if ($view->name == 'my_special_view' && user_access('administer site configuration') && $display_id == 'public_display') { $display_id = 'private_display'; } }
hook_views_pre_build(&$view)
Хук выполняется перед сборкой представления, в самом начале views::build()
. Дисплеи на этот момент уже инициализированы и выполнена их фаза views_plugin_display::pre_execute()
.
function hook_views_pre_build(&$view) { // Because of some unexplicable business logic, we should remove all // attachments from all views on Mondays. // (This alter could be done later in the execution process as well.) if (date('D') == 'Mon') { unset($view->attachment_before); unset($view->attachment_after); } }
hook_views_post_build(&$view)
Выполняется после сборки представления, в самом конце views::build()
. SQL запрос на этот момент уже построен, но ещё не передан в db_rewrite_sql()
.
function hook_views_post_build(&$view) { // If the exposed field 'type' is set, hide the column containing the content // type. (Note that this is a solution for a particular view, and makes // assumptions about both exposed filter settings and the fields in the view. // Also note that this alter could be done at any point before the view being // rendered.) if ($view->name == 'my_view' && isset($view->exposed_raw_input['type']) && $view->exposed_raw_input['type'] != 'All') { // 'Type' should be interpreted as content type. if (isset($view->field['type'])) { $view->field['type']->options['exclude'] = TRUE; } } }
hook_views_pre_execute(&$view)
Вызывается перед выполнением запроса, в самом начале view::execute()
. SQL запрос на этот момент уже построен, но ещё не передан в db_rewrite_sql()
.
function hook_views_pre_execute(&$view) { // Whenever a view queries more than two tables, show a message that notifies // view administrators that the query might be heavy. // (This action could be performed later in the execution process, but not // earlier.) if (count($view->query->tables) > 2 && user_access('administer views')) { drupal_set_message(t('The view %view may be heavy to execute.', array('%view' => $view->name)), 'warning'); } }
hook_views_query_alter(&$view, &$query)
Альтер-хук. Вызывается перед выполнением SQL запроса. Предназначен для изменения запросов.
function hook_views_query_alter(&$view, &$query) { // (Example assuming a view with an exposed filter on node title.) // If the input for the title filter is a positive integer, filter against // node ID instead of node title. if ($view->name == 'my_view' && is_numeric($view->exposed_raw_input['title']) && $view->exposed_raw_input['title'] > 0) { // Traverse through the 'where' part of the query. foreach ($query->where as &$condition_group) { foreach ($condition_group['conditions'] as &$condition) { // If this is the part of the query filtering on title, chang the // condition to filter on node ID. if ($condition['field'] == 'node.title') { $condition = array( 'field' => 'node.nid', 'value' => $view->exposed_raw_input['title'], 'operator' => '=', ); } } } } }
hook_views_post_execute(&$view)
Вызывается после выполнения запроса, в самом конце view::execute()
. Фаза pre_render()
для хендлеров ещё не выполнена.
function hook_views_post_execute(&$view) { // If there are more than 100 results, show a message that encourages the user // to change the filter settings. // (This action could be performed later in the execution process, but not // earlier.) if ($view->total_rows > 100) { drupal_set_message(t('You have more than 100 hits. Use the filter settings to narrow down your list.')); } }
hook_views_pre_render(&$view)
Вызывается перед рендерингом представления. pre_render()
фаза у хендлеров уже выполнена, поэтому все данные должны быть доступны.
function hook_views_pre_render(&$view) { // Scramble the order of the rows shown on this result page. // Note that this could be done earlier, but not later in the view execution // process. shuffle($view->result); }
hook_views_post_render(&$view, &$output, &$cache)
Вызывается после рендеринга данных.
function hook_views_post_render(&$view, &$output, &$cache) { // When using full pager, disable any time-based caching if there are less // then 10 results. if ($view->query->pager instanceof views_plugin_pager_full && $cache->options['type'] == 'time' && count($view->result) < 10) { $cache['options']['results_lifespan'] = 0; $cache['options']['output_lifespan'] = 0; } }
Полный список хуков.
Preprocess функции для представлений Views.
Комментарии
с template.php эти хуки вызываются?
Вызываются из template.php но почему то не все, pre_render да, а post_build нет. Странно. Наверно какое-то ограничение.
Подскажите, как можно программно изменить гурппировку во вьювс? Есть представление товаров, сгруппированное по полю "категория товара". Хочется в модуле в зависимости от некоторых условий убирать группировку.
Просмотрел через dsm() почти все хуки, но и близко не могу понять где там запрятна группировка по полю.
Пока нашел
function hook_preprocess_views_view_unformatted(&$vars) {
...
}
в этом хуке уже есть информация о группировке полей. Группировку можно убрать. Но что-то мне подсказывает, что группировку нужно отменять на более ранних этапах...
Здравствуйте, пытаюсь в function hook_views_pre_render(&$view) изменить image_style поля с изображением, ничего не происходит. Может другой хук нужен?
Стиль меняю так:
function HOOK_views_pre_render(&$view) {
if ($view->name == 'entertainment_slider' && $view->current_display == 'block_num_fond_preview') {
$detect = new Mobile_Detect;
if ($detect->isMobile() && !$detect->isTablet()) {
foreach ($view->result as $result_index => &$result_item) {
$result_item->field_field_img_slider[0]['rendered']['#image_style'] = 'i767x396';
}
}
}
}
Где можно посмотреть информацию, как правильно использовать delta для множественных условий для одного поля в запросе.
db_and()
->condition('node__field_name.field_name_target_id', $array, 'IN')
->condition('node__field_name.field_name_target_id', $array, 'IN')
->condition('node__field_name.field_name_target_id', $array, 'IN');
Оставить комментарий