
Drupal Views 简明开发指引
Drupal 使用 Views 模块来罗列内容,内容可以基于 Entity,也可以基于模块自定义的数据表。通常一个 view 对应一类列表,比如文章列表。
准备
开发 views 相关模块,首先需要通过 hook_views_api 函数声明 view 的定义及 view 的相关模版的存放路径,这个函数通常放在模块的 .module 文件中。
/**
* Implements hook_views_api().
*
* Declares location of defines and templates for views.
*/
function moha_clip_views_api() {
return array(
'api' => 3, // 需要调用的 Views API 的版本
'path' => MOHA_CLIP__RELATIVE_PATH . '/views', // view 的定义存放路径
'template path' => MOHA_CLIP__RELATIVE_PATH . '/templates', // view 的主题模版存放路径
);
}
罗列 Entity 内容
Views 罗列 Entity 内容,可以通过 views_ui 先行构建一个 view,然后导出至自定义模块的 hook_views_default_views 函数即可使用。
罗列数据表中的内容
罗列模块自定义的数据表可以通过 hook_views_data 函数,该函数需要放在 <Module Name>.views.inc 文件中。该函数返回一个数组,表的名字作为数组的 Key。
/**
* Implements hook_views_data().
*
* Exposes table moha_wx_accounts to views.
*
* @return array
*/
function moha_wx_views_data() {
$data = array();
// Table: moha_wx_accounts.
$data['moha_wx_accounts']['table']['group'] = t('Moha WeChat account'); // Group name before field name.
$data['moha_wx_accounts']['table']['base'] = array ( // Entry for creating views.
'title' => t('Moha WeChat accounts'),
'help' => t('Records of Moha WeChat accounts.'),
);
// User ID / 'uid' field, @see user.views.inc.
$data['moha_wx_accounts']['uid'] = array(
'title' => t('Owner'),
'help' => t('The user who owns the account. If you need more fields than the uid add the content: owner relationship'),
'field' => array(
'handler' => 'views_handler_field_user',
),
'argument' => array(
'handler' => 'views_handler_argument_numeric',
),
'sort' => array(
'handler' => 'views_handler_sort',
),
'filter' => array(
'handler' => 'views_handler_filter_user_name',
),
// Declares relationship which can be added later on views_ui.
'relationship' => array(
'base' => 'users',
'field' => 'uid',
'title' => t('Owner'),
'help' => t('Relate account to the user who owns it.'),
'handler' => 'views_handler_relationship',
'label' => t('Owner'),
),
);
// Text field: see https://www.moha.online/help/views/api-tables.
$data['moha_wx_accounts']['account_name'] = array(
'title' => t('Account name'),
'help' => t('Human readable account name.'),
// 不同的字段需要从 <Views 模块安装目录>/handlers 目录下选取合适的 Handler 来显示、排序、过滤该字段.
'field' => array(
'handler' => 'views_handler_field',
),
'sort' => array(
'handler' => 'views_handler_sort',
),
'filter' => array(
'handler' => 'views_handler_filter_string',
),
);
// Timestamp field.
$data['moha_wx_accounts']['access_token_updated'] = array(
'title' => t('Access Token Refreshed Time'),
'help' => t('Stores timestamp when access token is refreshed.'),
'field' => array(
'handler' => 'views_handler_field_date',
),
'sort' => array(
'handler' => 'views_handler_sort_date',
),
'filter' => array(
'handler' => 'views_handler_filter_date',
),
);
return $data;
}
自定义 Handler