Skip to content

Drupal Views

andyceo edited this page Aug 18, 2015 · 2 revisions

Drupal Views 2 API

Т.к. львиная доля документации Views лежит вместе с ним же, в файлах помощи Advanced Help, то мы будем давать ссылки непосредственно на страницы помощи, предполагая, что Views у нас установлен на домене http://dservers.ruware.com/

Документация на английском:

Статьи на русском:

  • Первая
  • Вторая

Отобразить Views программно

function my_func() {
  $view = views_get_view('my_view');
  $view->set_display('default');
  $view->args[0] = '1,2,3,4' // list of the arguments
  $view->pre_execute();
  return $view->render();
}

Хуки

/** * Структура таблиц views описывается в этом хуке. * * http://archive.chriscar.com/system/files/1/67.archive/67.html * * Должен быть в файле MODULENAME.views.inc и будет загружен автоматически. Файл * должен быть в той же директории, что и файл .module, или в поддиректории 'includes'. * * Полная документация в advanced help. * http://views-help.doc.logrus.com/help/views/api-tables * http://dservers.ruware.com/help/views/api-tables?popup=1 */ function hook_views_data() {}

/** * *

  • Должен быть в файле MODULENAME.views.inc и будет загружен автоматически. Файл
  • должен быть в той же директории, что и файл .module, или в поддиректории 'includes'.
  • Полная документация в advanced help.
  • This is a stub list as a reminder that this needs to be doc'd and is not used
  • in views anywhere so might not be remembered when this is formally documented:
    • style: 'even empty' */ function hook_views_plugins() { // example code here }

/**

  • Переопределяет существующие плагины, которые были определенны модулями. */ function hook_views_plugins_alter(&$plugins) { // Add apachesolr to the base of the node row plugin. $plugins['row']['node']['base'][] = 'apachesolr'; }

/**

  • Регистрирует хендлер(ы), информацию о файле, где хранится хендлер и
  • информацию о его родителе (родительском классе), так что хендлер может
  • быть загружен только по запросу.
  • Полная документация в advanced help:
  • http://dservers.ruware.com/help/views/api-handlers?popup=1
  • Возвращает массив (см. пример кода)

*/ function hook_views_handlers() { // example code here return array( 'info' => array( 'path' => drupal_get_path('module', 'YOURMODULE') .'/views', ), 'handlers' => array( 'YOURMODULE_handler_argument_YOURARGUMENT' => array( 'parent' => 'views_handler_argument_string', ), 'YOURMODULE_handler_filter_YOURFILTER' => array( 'parent' => 'views_handler_filter_numeric', ), ), ); // end of example code }

/**

  • Регистрирует информацию о View API. Это требуется для того, чтобы inc-файлы
  • вашего модуля загрузились, например, когда вы реализуете
  • hook_views_default_views().
  • @return
  • An array with the following possible keys:
    • api: (required) The version of the Views API the module implements.
    • path: (optional) If includes are stored somewhere other than within
  •   the root module directory or a subdirectory called includes, specify
    
  •   its path here.
    

*/ function hook_views_api() { return array( 'api' => 2, 'path' => drupal_get_path('module', 'example') . '/includes/views', ); }

/**

  • This hook allows modules to provide their own views which can either be used
  • as-is or as a "starter" for users to build from.
  • This hook should be placed in MODULENAME.views_default.inc and it will be
  • auto-loaded. This must either be in the same directory as the .module file
  • or in a subdirectory named 'includes'.
  • The $view->disabled boolean flag indicates whether the View should be
  • enabled or disabled by default.
  • @return
  • An associative array containing the structures of views, as generated from
  • the Export tab, keyed by the view name. A best practice is to go through
  • and add t() to all title and label strings, with the exception of menu
  • strings. */ function hook_views_default_views() { // Begin copy and paste of output from the Export tab of a view. $view = new view; $view->name = 'frontpage'; $view->description = t('Emulates the default Drupal front page; you may set the default home page path to this view to make it your front page.'); $view->tag = t('default'); $view->view_php = ''; $view->base_table = 'node'; $view->is_cacheable = '0'; $view->api_version = 2; $view->disabled = FALSE; // Edit this to true to make a default view disabled initially $view->display = array(); $display = new views_display; $display->id = 'default'; $display->display_title = t('Defaults'); $display->display_plugin = 'default'; $display->position = '1'; $display->display_options = array ( 'style_plugin' => 'default', 'style_options' => array ( ), 'row_plugin' => 'node', 'row_options' => array ( 'teaser' => 1, 'links' => 1, ), 'relationships' => array ( ), 'fields' => array ( ), 'sorts' => array ( 'sticky' => array ( 'id' => 'sticky', 'table' => 'node', 'field' => 'sticky', 'order' => 'ASC', ), 'created' => array ( 'id' => 'created', 'table' => 'node', 'field' => 'created', 'order' => 'ASC', 'relationship' => 'none', 'granularity' => 'second', ), ), 'arguments' => array ( ), 'filters' => array ( 'promote' => array ( 'id' => 'promote', 'table' => 'node', 'field' => 'promote', 'operator' => '=', 'value' => '1', 'group' => 0, 'exposed' => false, 'expose' => array ( 'operator' => false, 'label' => '', ), ), 'status' => array ( 'id' => 'status', 'table' => 'node', 'field' => 'status', 'operator' => '=', 'value' => '1', 'group' => 0, 'exposed' => false, 'expose' => array ( 'operator' => false, 'label' => '', ), ), ), 'items_per_page' => 10, 'use_pager' => '1', 'pager_element' => 0, 'title' => '', 'header' => '', 'header_format' => '1', 'footer' => '', 'footer_format' => '1', 'empty' => '', 'empty_format' => '1', ); $view->display['default'] = $display; $display = new views_display; $display->id = 'page'; $display->display_title = t('Page'); $display->display_plugin = 'page'; $display->position = '2'; $display->display_options = array ( 'defaults' => array ( 'access' => true, 'title' => true, 'header' => true, 'header_format' => true, 'header_empty' => true, 'footer' => true, 'footer_format' => true, 'footer_empty' => true, 'empty' => true, 'empty_format' => true, 'items_per_page' => true, 'offset' => true, 'use_pager' => true, 'pager_element' => true, 'link_display' => true, 'php_arg_code' => true, 'exposed_options' => true, 'style_plugin' => true, 'style_options' => true, 'row_plugin' => true, 'row_options' => true, 'relationships' => true, 'fields' => true, 'sorts' => true, 'arguments' => true, 'filters' => true, 'use_ajax' => true, 'distinct' => true, ), 'relationships' => array ( ), 'fields' => array ( ), 'sorts' => array ( ), 'arguments' => array ( ), 'filters' => array ( ), 'path' => 'frontpage', ); $view->display['page'] = $display; $display = new views_display; $display->id = 'feed'; $display->display_title = t('Feed'); $display->display_plugin = 'feed'; $display->position = '3'; $display->display_options = array ( 'defaults' => array ( 'access' => true, 'title' => false, 'header' => true, 'header_format' => true, 'header_empty' => true, 'footer' => true, 'footer_format' => true, 'footer_empty' => true, 'empty' => true, 'empty_format' => true, 'use_ajax' => true, 'items_per_page' => true, 'offset' => true, 'use_pager' => true, 'pager_element' => true, 'use_more' => true, 'distinct' => true, 'link_display' => true, 'php_arg_code' => true, 'exposed_options' => true, 'style_plugin' => false, 'style_options' => false, 'row_plugin' => false, 'row_options' => false, 'relationships' => true, 'fields' => true, 'sorts' => true, 'arguments' => true, 'filters' => true, ), 'relationships' => array ( ), 'fields' => array ( ), 'sorts' => array ( ), 'arguments' => array ( ), 'filters' => array ( ), 'displays' => array ( 'default' => 'default', 'page' => 'page', ), 'style_plugin' => 'rss', 'style_options' => array ( 'mission_description' => 1, 'description' => '', ), 'row_plugin' => 'node_rss', 'row_options' => array ( 'item_length' => 'default', ), 'path' => 'rss.xml', 'title' => t('Front page feed'), ); $view->display['feed'] = $display; // End copy and paste of Export tab output.

// Add view to list of views to provide. $views[$view->name] = $view;

// ...Repeat all of the above for each view the module should provide.

// At the end, return array of default views. return $views; }

/**

  • This hook is called right before all default views are cached to the
  • database. It takes a keyed array of views by reference. */ function hook_views_default_views_alter(&$views) { if (isset($views['taxonomy_term'])) { $views['taxonomy_term']->set_display('default'); $views['taxonomy_term']->display_handler->set_option('title', 'Categories'); } }

/**

  • Stub hook documentation
  • Converting views1 views to views2.
  • @link http://archive.chriscar.com/system/files/1/67.archive/67.html @endlink
  • This hook should be placed in MODULENAME.views_convert.inc and it will be auto-loaded.
  • This must either be in the same directory as the .module file or in a subdirectory
  • named 'includes'. */ function hook_views_convert() { // example code here }

/**

  • Stub hook documentation
  • Query substitutions */ function hook_views_query_substitutions() { // example code here }

/**

  • This hook is called at the very beginning of views processing,
  • before anything is done.
  • Adding output to the view can be accomplished by placing text on
  • $view->attachment_before and $view->attachment_after. */ function hook_views_pre_view(&$view, &$display_id, &$args) { // example code here }

/**

  • This hook is called right before the build process, but after displays
  • are attached and the display performs its pre_execute phase.
  • Adding output to the view can be accomplished by placing text on
  • $view->attachment_before and $view->attachment_after. */ function hook_views_pre_build(&$view) { // example code here }

/**

  • This hook is called right before the execute process. The query is
  • now fully built, but it has not yet been run through db_rewrite_sql.
  • Adding output to the view can be accomplished by placing text on
  • $view->attachment_before and $view->attachment_after. */ function hook_views_pre_execute(&$view) { // example code here }

/**

  • This hook is called right before the render process. The query has
  • been executed, and the pre_render() phase has already happened for
  • handlers, so all data should be available.
  • Adding output to the view can be accomplished by placing text on
  • $view->attachment_before and $view->attachment_after. Altering the
  • content can be achieved by editing the items of $view->result.
  • This hook can be utilized by themes. */ function hook_views_pre_render(&$view) { // example code here }

/**

  • Post process any rendered data.
  • This can be valuable to be able to cache a view and still have some level of
  • dynamic output. In an ideal world, the actual output will include HTML
  • comment based tokens, and then the post process can replace those tokens.
  • Example usage. If it is known that the view is a node view and that the
  • primary field will be a nid, you can do something like this:
  • And then in the post render, create an array with the text that should
  • go there:
  • strtr($output, array('', 'output for FIELD of nid 1');
  • All of the cached result data will be available in $view->result, as well,
  • so all ids used in the query should be discoverable.
  • This hook can be utilized by themes. */ function hook_views_post_render(&$view, &$output, &$cache) {

}

/**

  • Stub hook documentation
  • This hook should be placed in MODULENAME.views.inc and it will be auto-loaded.
  • This must either be in the same directory as the .module file or in a subdirectory
  • named 'includes'.

*/ function hook_views_query_alter(&$view, &$query) { // example code here }

/**

  • This hook should be placed in MODULENAME.views.inc and it will be auto-loaded.
  • This must either be in the same directory as the .module file or in a subdirectory
  • named 'includes'.
  • Alter the links that appear over a view. They are in a format suitable for
  • theme('links').
  • Warning: $view is not a reference in PHP4 and cannot be modified here. But it IS
  • a reference in PHP5, and can be modified. Please be careful with it.
  • @see theme_links */ function hook_views_admin_links_alter(&$links, $view) { // example code here }

/**

  • This hook should be placed in MODULENAME.views.inc and it will be auto-loaded.
  • This must either be in the same directory as the .module file or in a subdirectory
  • named 'includes'.
  • Alter the rows that appear with a view, which includes path and query information.
  • The rows are suitable for theme('table').
  • Warning: $view is not a reference in PHP4 and cannot be modified here. But it IS
  • a reference in PHP5, and can be modified. Please be careful with it.
  • @see theme_table */ function hook_views_preview_info_alter(&$rows, $view) { // example code here }

===== Хэндлеры (handlers) =====

/* * Этот хендлер дополняет стандартный хендлер булевого поля новым способом * отображения информации: 0/1. */ class views_handler_field_boolean_sep extends views_handler_field_boolean { function init(&$view, $options) { parent::init($view, $options); $sep_format = array( '1-0' => array('1', '0'), ); $this->formats = array_merge($this->formats, $sep_format); }

function option_definition() { $options = parent::option_definition(); $options['type'] = array('default' => '1-0'); return $options; } }

===== Динамическое (программное) добавление поля в существующий default views =====

Концепция: default-views`ы - это вьюсы, которые определены в коде (всего существует три категории вьюсов: normal (созданные через UI и хранящиеся в БД изначально), default (определенные в коде), overriden (переопределенные default)). Но все они всё равно хранятся в БД. Чтобы из другого модуля (не из того, где вьюс определен), добавить поле к дефолт-вьюсу, надо на этапе сохранения вьюса в базу, добавить это поле. Делается это через реализацию хука ''hook_views_default_views_alter()'', который дергается только когда вьюс кешируется и кладется в БД:

/* * Реализация функции hook_views_default_views_alter() */ function MODULENAME_views_default_views_alter(&$views) { if (isset($views['VIEWNAME'])) { //убеждаемся, что тот views, в который надо добавить поле, существует /* * Основные настройки поля, которые надо задавать для любого поля. * Данные настройки при использовании метода $views->add_item() должны * передаваться в качестве аргументов. */ $options = array( 'id' => 'my_field_id', // если не задано, будет сгенерено views`ом 'field' => 'tid', // физическое поле в таблице в БД, с которым ассоциируется данное поле views 'table' => 'term_node', // таблица, где находится физическое поле );
/*
 * Массив настроек для поля типа "Taxonomy: All terms"
 * 
 * В общем случае, нужные настройки можно узнать, создав поле вручную и затем экпортировав views.
 */
$options2 = array(
  'label' => t('My Field Name'),
  'empty' => '',
  'hide_empty' => 0,
  'empty_zero' => 0,
  'type' => 'separator',
  'separator' => ', ',
  'link_to_taxonomy' => 0,
  'limit' => 1,
  'vids' => array(
    '5' => '5', //нам нужно отобразить термины только из словаря vid = 5
  ),
  'exclude' => 0,
  'relationship' => 'none',
  'alter' => array(
    'alter_text' => 0,
    'text' => '',
    'make_link' => 0,
    'path' => '',
    'link_class' => '',
    'alt' => '',
    'prefix' => '',
    'suffix' => '',
    'target' => '',
    'help' => '',
    'trim' => 0,
    'max_length' => '',
    'word_boundary' => 1,
    'ellipsis' => 1,
    'html' => 0,
    'strip_tags' => 0,
  ),
);
$views['VIEWNAME']->display['default']->display_options['fields']['my_field_id'] = array_merge($options, $options2); //обратите внимание на использование нужного display и для чего нам нужен жестко заданный id поля.

//$views['VIEWNAME']->add_item('default', 'field', 'term_node', 'tid', $options2, 'my_field_id'); //должно работать, но не работает!

} }

А теперь поподробнее про последнюю закомментированную строчку: ''$views['VIEWNAME']->add_item('default', 'field', 'term_node', 'tid', $options2, 'my_field_id');''

Использовать ''$views->add_item'' было посоветовано здесь: http://drupal.org/node/912762, правда, в другом хуке ''hook_views_pre_build()'' или ''hook_views_query_alter()''. Если использовать этот метод, то он также корректно работает, но при заходе на страничку со http://example.com/admin/build/views (или на какую-нибудь еще страницу, ошибка проявляется случайно), мы получаем ошибку вида

PHP Fatal error: view::get_path(): The script tried to execute a method or access a property of an incomplete object. Please ensure that the class definition "views_plugin_display_default" of the object you are trying to operate on was loaded before unserialize() gets called or provide a __autoload() function to load the class definition in /var/www/drupal6/sites/all/modules/contrib/views/includes/view.inc on line 1181, referer: http://example.com/admin/build/views

Это происходит из-за того, что add_item() добавляет ко views дополнительный handler к display, и потом сохраняет этот views в БД (все default-views сохраняются (кешируются) в БД). Затем, когда views требуется, он извлекается из базы и рассериализуется, однако handler`а в этот момент не существует и происходит ошибка, при обращении к неизвестному методу. Views должен сохраняться без этого хендлера, во избежание проблем.

Поэтому, используется простое добавление поля в массив полей нужного display.

===== Добавляем фильтры ===== ==== Ссылки ====

====== Views 3 (Drupal 7) ======

Views 3 usefull links:

Sidebar is under construction

Clone this wiki locally