Что такое плагин Ctools (тип контента, доступ и т. Д.) И как их создавать?
Что такое плагины Ctools и как их создавать?
2 ответа
Время от времени при работе с менеджером страниц Ctools и Панели , полезно добавить пользовательские плагины Ctools.
Плагины Ctools поставляются в большом количестве форм, а также другие модули, такие как Каналы , Адресное поле и Openlayers используют Ctools для обеспечения расширения плагинов другими модулями. Однако наиболее распространенными формами плагина являются «тип контента» и «доступ». Первый должен не путать с сущностью «content» и ее пакетами, также называемыми типами контента.
Во-первых, шаблон :
Для любого модуля, предоставляющего плагины ctools, они должны сначала указать Ctools, где их искать. Крючок ниже, говорит, что мы предоставляем плагины для ctools, типов «content_types» и «access». Функция может быть упрощена, но таким образом мы гарантируем, что только плавный модуль будет информирован о правильном модуле, а также будет проверять диск на наличие файлов, когда мы действительно предоставляем тип запрашиваемого плагина.
function HOOK_ctools_plugin_directory($owner, $plugin_type) {
// We'll be nice and limit scandir() calls.
if ($owner == 'ctools' && ($plugin_type == 'content_types' || $plugin_type == 'access')) {
return 'plugins/' . $plugin_type;
}
}
Ниже приведен пример структуры каталогов для модуля, содержащего два плагина. Один тип контента и один плагин доступа.
module/
module/module.info
module/module.module
module/plugins/
module/plugins/content_types/
module/plugins/content_types/two_views_in_one.inc
module/plugins/access/
module/plugins/access/term_depth.inc
Плагин типа содержимого
Тип контента в словаре Ctools чаще всего называется «Панели», как предусмотрено, например, Views. В этом вопросе: Есть ли способ перехватить список NID, созданный представлением, и использовать их в качестве фильтра для другого представления? , автор спрашивает о программном подавая аргументы в точку зрения. В то время как это в нем само по себе не очень сложно, быстро возникает следующий вопрос: «Как показать результаты?».
Один из ответов - создать новый «тип контента».
Теперь фактический плагин типа контента, снова используя вопрос «Представления» сверху, может выглядеть так:
$plugin = array(
'title' => t('Render a View with arguments from another'),
'single' => TRUE,
'category' => array(t('My custom category'), -9),
// Despite having no "settings" we need this function to pass back a form, or we'll loose the context and title settings.
'edit form' => 'module_content_type_edit_form',
'render callback' => 'module_content_type_render',
);
function module_content_type_render($subtype, $conf, $args, $context = NULL) {
$block = new stdClass;
$block->title = 'My View';
$view = views_get_view('get_nids');
$view->preview('display_machine_name', array($arg1, $arg2));
$nids = '';
foreach($view->result as $node) {
$nids += $node->nid . ',';
}
$nids = rtrim($nids, ',');
$view = views_get_view('get_related');
$view->execute_display('display_machine_name', array($nids));
$block->content = $view->render();
return $block;
}
/**
* 'Edit form' callback for the content type.
*/
function module_content_type_edit_form($form, &$form_state) {
// No settings beyond context, which has already been handled.
return $form;
}
При включенном модуле теперь должна быть новая категория в панелях «Моя пользовательская категория», в которой нужно найти одну панель, отображая код сверху.
Плагин доступа
Плагин доступа ниже предоставит возможность фильтровать варианты и /или панели в зависимости от глубины слова, измеренного от корня словаря.
<?php
/**
* @file
* Plugin to provide access control based upon a parent term.
*/
/**
* Plugins are described by creating a $plugin array which will be used
* by the system that includes this file.
*/
$plugin = array(
'title' => t("Taxonomy: term depth"),
'description' => t('Control access by the depth of a term.'),
'callback' => 'term_depth_term_depth_ctools_access_check',
'default' => array('vid' => array(), 'depth' => 0),
'settings form' => 'term_depth_term_depth_ctools_access_settings',
'settings form validation' => 'term_depth_term_depth_ctools_access_settings_validate',
'settings form submit' => 'term_depth_term_depth_ctools_access_settings_submit',
'summary' => 'term_depth_term_depth_ctools_access_summary',
'required context' => new ctools_context_required(t('Term'), array('taxonomy_term', 'terms')),
);
/**
* Settings form for the 'term depth' access plugin.
*/
function term_depth_term_depth_ctools_access_settings($form, &$form_state, $conf) {
// If no configuration was saved before, set some defaults.
if (empty($conf)) {
$conf = array(
'vid' => 0,
);
}
if (!isset($conf['vid'])) {
$conf['vid'] = 0;
}
// Loop over each of the configured vocabularies.
foreach (taxonomy_get_vocabularies() as $vid => $vocabulary) {
$options[$vid] = $vocabulary->name;
}
$form['settings']['vid'] = array(
'#title' => t('Vocabulary'),
'#type' => 'select',
'#options' => $options,
'#description' => t('Select the vocabulary for this form. If there exists a parent term in that vocabulary, this access check will succeed.'),
'#id' => 'ctools-select-vid',
'#default_value' => $conf['vid'],
'#required' => TRUE,
);
$form['settings']['depth'] = array(
'#title' => t('Depth'),
'#type' => 'textfield',
'#description' => t('Set the required depth of the term. If the term exists at the right depth, this access check will succeed.'),
'#default_value' => $conf['depth'],
'#required' => TRUE,
);
return $form;
}
/**
* Submit function for the access plugins settings.
*
* We cast all settings to numbers to ensure they can be safely handled.
*/
function term_depth_term_depth_ctools_access_settings_submit($form, $form_state) {
foreach (array('depth', 'vid') as $key) {
$form_state['conf'][$key] = (integer) $form_state['values']['settings'][$key];
}
}
/**
* Check for access.
*/
function term_depth_term_depth_ctools_access_check($conf, $context) {
// As far as I know there should always be a context at this point, but this
// is safe.
if (empty($context) || empty($context->data) || empty($context->data->vid) || empty($context->data->tid)) {
return FALSE;
}
// Get the $vid.
if (!isset($conf['vid'])) {
return FALSE;
}
$depth = _term_depth($context->data->tid);
return ($depth == $conf['depth']);
}
/**
* Provide a summary description based upon the checked terms.
*/
function term_depth_term_depth_ctools_access_summary($conf, $context) {
$vocab = taxonomy_vocabulary_load($conf['vid']);
return t('"@term" has parent in vocabulary "@vocab" at @depth', array(
'@term' => $context->identifier,
'@vocab' => $vocab->name,
'@depth' => $conf['depth'],
));
}
/**
* Find the depth of a term.
*/
function _term_depth($tid) {
static $depths = array();
if (!isset($depths[$tid])) {
$parent = db_select('taxonomy_term_hierarchy', 'th')
->fields('th', array('parent'))
->condition('tid', $tid)
->execute()->fetchField();
if ($parent == 0) {
$depths[$tid] = 1;
}
else {
$depths[$tid] = 1 + _term_depth($parent);
}
}
return $depths[$tid];
}
Плагины CTools - это небольшие файлы, которые могут быть частью любого модуля как способ расширения его функциональности. Они могут использоваться для предоставления компонентов (панелей), добавления дополнительных параметров стилей к вашим панелям и т. Д.
Пожалуйста, просмотрите плагины CTools без панелей для пошаговой документации. Поэтому коротко это выглядит так:
-
Вам нужно добавить зависимости CTools в ваш
.info
файл как:dependencies[] = ctools dependencies[] = panels
-
Скажите CTools, где находится ваш плагин:
<?php function MYMODULE_ctools_plugin_directory($module, $plugin) { if (($module == 'ctools') && ($plugin == 'content_types')) { return 'plugins/content_types'; } } ?>
-
Внедрить плагин в файле
.inc
(по умолчанию в качестве$module.$api.inc
). Пример кода плагина:<?php $plugin = array( 'title' => t('Twitter feed'), 'description' => t('Twitter feed'), 'category' => 'Widgets', 'icon' => '', 'render callback' => 'twitter_block', 'defaults' => array(), ); // render callback function twitter_block() { // Add twitter widget javascript $url = TWITTER_USER $widget_id = TWITTER_WIDGET_ID; $data = array(); $data['url'] = $url; $data['widget_id'] = $widget_id; $content = array( '#theme' => 'my_block', '#content' => $data, ); $block = new stdClass(); $block->content = $content; $block->title = ''; $block->id = 'twitter_block'; return $block; } ?>
Расположение плагинов по умолчанию выглядит следующим образом:
MYMODULE/
plugins/
content_types/
templates/
MYMODULE.info
MYMODULE.module
Дополнительные примеры см. в ctools_plugin_example
, который как часть модуля CTools, или проверить страницу справки ( Примеры плагинов CTools ) в интерфейсе Drupal после включения модуля.
В Drupal 8 это теперь часть ядра (см. Drupal \ Component \ Plugin ), и он обеспечивает наследование объектов, интерфейсы объектов и инкапсуляцию отдельных файлов. См .: Drupal 8 Теперь: объектно-ориентированные плагины в Drupal 7