
Views module - API. The basics
Surely, many people working with Drupal are familiar with the Views module . As Drupaler.ru says , the Views module is Setting up and controlling the display of any type of content anywhere on the site , i.e. it allows you to create pages, blocks, replace the contents of nodes, user pages and much more, forming content from any available fields on the site. But what to do when it is necessary to display information provided by a third-party module, and to which we do not have access from Views?
To make it clear, then everything is based on a living example:
On the site I use the PrivateMSG module. It allows users to send each other private messages. Using Views, I put together a block that displays information about the current user.
Task: Display in the block the number of new messages and the number of all messages in the Inbox of the current user.
Solution: Write a module that adds the necessary values to the Views constructor.
Unfortunately on the Internet, there is very little information about this, and the Views API manual is rather complicated and incomprehensible.
So let's get started.
After all that has been done, Views will form a request of type
and will return the necessary values.
I hope the instruction will be useful to someone. If there is interest, I can write in more detail about Views, there is still a lot of interesting things: how to create your own settings for fields, how to create fields available in filters and sorts, your arguments and relationships, and much more.
UPD: Moved to the Drupal blog. Thanks for the karma.
To make it clear, then everything is based on a living example:
On the site I use the PrivateMSG module. It allows users to send each other private messages. Using Views, I put together a block that displays information about the current user.
Task: Display in the block the number of new messages and the number of all messages in the Inbox of the current user.
Solution: Write a module that adds the necessary values to the Views constructor.
Unfortunately on the Internet, there is very little information about this, and the Views API manual is rather complicated and incomprehensible.
So let's get started.
- Create a new module.
As expected, create a directory, call it the name of our future module. I called it privatemsg_extraviews .
In the directory, we create the files privatemsg_extraviews.info, privatemsg_extraviews.module, privatemsg_extraviews.views.inc . Next, we need to create 2 more files, but more on that later. - privatemsg_extraviews.info
This file contains information about our module. I need Drupal to recognize the module.name = privatemsg_extraviews
description = Добавляет поддержку views в Private Messages
core = 6.x
package = Mail
version = "6.x-1.1"
* This source code was highlighted with Source Code Highlighter.
This is enough for Drupal to recognize our module. - privatemsg_extraviews.module
The main module file. It writes the entire structure of the module, all the hooks, and generally everything.
We only need to indicate that the module works with Views.
/**
* Implementation of hook_views_api().
*/
function privatemsg_extraviews_views_api() {
return array(
'api' => 2, // Указываем версию API
'path' => drupal_get_path('module', 'privatemsg_extraviews'), // Указываем откуда брать файл для Views
);
}
* This source code was highlighted with Source Code Highlighter. - privatemsg_extraviews.views.inc
The most interesting. In this file we write the entire system of working with Views. The module itself will find it, because we specified the directory in the hook above.
The main hook we need is hook_views_data () . In it, we determine which database table we add and what information we return.function privatemsg_extraviews_views_data() {
// Определяем новую группу во Views
$data['privatemsg']['table']['group'] = t('Private Messages');
// Указываем таблицы
$data['privatemsg']['table']['join'] = array(
// users - значит наши значения будут доступны только при выборке пользователей
'users' => array(
// Указываем ключи
'left_field' => 'uid',
'field' => 'uid',
),
);
// count - столбец таблицы, по которому будет выборка
$data['privatemsg']['count'] = array(
'title' => t('Количество входящих сообщений'),
'help' => t('Количество сообщений в папке "Входящие"'),
// Указываем возвращаемое поле
'field' => array(
// Обработчик для этого поля
'handler' => 'privatemsg_extraviews_handler_field_count',
// Доступна сортировка по этому полю
'click sortable' => TRUE,
),
);
// Аналогично
$data['privatemsg']['count_new'] = array(
'title' => t('Количество новых сообщений'),
'help' => t('Количество новых сообщений в папке "Входящие"'),
'field' => array(
'handler' => 'privatemsg_extraviews_handler_field_count_new',
'click sortable' => TRUE,
),
);
return $data;
}
* This source code was highlighted with Source Code Highlighter.
Next, we need hook_views_handlers () to initialize the field handlers.function privatemsg_extraviews_views_handlers() {
return array(
// Обработчики
'handlers' => array(
'privatemsg_extraviews_handler_field_count' => array(
// Указываем, что возвращаем числовое значение
'parent' => 'views_handler_field_numeric',
// И путь к файлу обработчика
'path' => drupal_get_path('module', 'privatemsg_extraviews'),
),
// Аналогично
'privatemsg_extraviews_handler_field_count_new' => array(
'parent' => 'views_handler_field_numeric',
'path' => drupal_get_path('module', 'privatemsg_extraviews'),
),
),
);
}
* This source code was highlighted with Source Code Highlighter.
As I said above, we will need to create 2 more files - these are just the field handlers. Create the files privatemsg_extraviews_handler_field_count.inc and privatemsg_extraviews_handler_field_count_new.inc in the directory of the module . - privatemsg_extraviews_handler_field_count.inc
Handler for the "Number of messages" field.// Определяем обработчик, наследуем от стандартного класса "числовое значение"
class privatemsg_extraviews_handler_field_count extends views_handler_field_numeric {
// Запрос к БД
function query() {
// Определяем таблицу
$table = $this->query->ensure_table('pm_index');
// Запрашиваем количество сообщений
$sql = "SELECT COUNT(DISTINCT thread_id) FROM {pm_index} p WHERE p.deleted = 0 AND p.uid = users.uid";
// Указываем название для возвращаемого поля
$this->query->add_field('', "($sql)", 'count');
$this->field_alias = 'count';
}
// Возвращаем полученное значение
function render($values) {
$txt = $values->count;
if ($txt) {
return $txt;
}
else {
return parent::render($values);
}
}
}
* This source code was highlighted with Source Code Highlighter. - privatemsg_extraviews_handler_field_count_new.inc
Handler for the "Number of new posts" field. (similarly)
class privatemsg_extraviews_handler_field_count_new extends views_handler_field_numeric {
function query() {
$table = $this->query->ensure_table('pm_index');
$sql = "SELECT COUNT(DISTINCT thread_id) FROM {pm_index} p WHERE p.deleted = 0 AND p.is_new = 1 AND p.uid = users.uid";
$this->query->add_field('', "($sql)", 'count_new');
$this->field_alias = 'count_new';
}
function render($values) {
$txt = $values->count_new;
if ($txt) {
return $txt;
}
else {
return parent::render($values);
}
}
}
* This source code was highlighted with Source Code Highlighter.
After all that has been done, Views will form a request of type
SELECT users.uid AS uid,
(SELECT COUNT(DISTINCT thread_id) FROM pm_index p WHERE p.deleted = 0 AND p.uid = users.uid) AS count,
(SELECT COUNT(DISTINCT thread_id) FROM pm_index p WHERE p.deleted = 0 AND p.is_new = 1 AND p.uid = users.uid) AS count_new
FROM users users
WHERE users.uid = 1
* This source code was highlighted with Source Code Highlighter.
and will return the necessary values.
I hope the instruction will be useful to someone. If there is interest, I can write in more detail about Views, there is still a lot of interesting things: how to create your own settings for fields, how to create fields available in filters and sorts, your arguments and relationships, and much more.
UPD: Moved to the Drupal blog. Thanks for the karma.