显示套件:掌握Drupal 8
>中的自定义字段创建> Display Suite(DS)仍然是Drupal贡献模块的基石,为制作网站布局提供了强大的工具并管理内容演示文稿。 它的强度在于创建与DS布局中核心字段值一起显示的自定义字段。 该功能在Drupal 7中高度重视,在Drupal 8中继续和扩展,利用了新的面向对象的编程(OOP)体系结构和插件系统。本指南详细介绍了Drupal 8中创建自定义DS字段
> drupal 8插件和DS字段插件类型>
> Drupal 8的插件系统取代了Drupal 7的>插件类型。 我们不是_info
,而是在其方法的注释和逻辑中构建一个带有元数据的插件类。DsField
>
hook_ds_field_info()
插件类VocabularyTerms
>
>我们的示例创建了一个DS字段(在名为“演示”的自定义模块中),显示了可配置词汇的分类术语,仅限于文章节点。 插件类(
>中,并注释如下:VocabularyTerms
src/plugins/DsField
namespace Drupal\demo\Plugin\DsField; use Drupal\ds\Plugin\DsField\DsFieldBase; /** * Plugin displaying terms from a selected taxonomy vocabulary. * * @DsField( * id = "vocabulary_terms", * title = @Translation("Vocabulary Terms"), * entity_type = "node", * provider = "demo", * ui_limit = {"article|*"} * ) */ class VocabularyTerms extends DsFieldBase { }
为了允许词汇选择,我们实现了设置默认词汇(“ tags”):
defaultConfiguration()
formatters(例如,链接或未链接的术语列表)是使用
/** * {@inheritdoc} */ public function defaultConfiguration() { return ['vocabulary' => 'tags']; }
formatters()
/** * {@inheritdoc} */ public function formatters() { return ['linked' => 'Linked', 'unlinked' => 'Unlinked']; }
>配置摘要和设置表单
>
方法提供了所选配置的UI摘要:
settingsSummary()
/** * {@inheritdoc} */ public function settingsSummary($settings) { $config = $this->getConfiguration(); return isset($config['vocabulary']) && $config['vocabulary'] ? ['Vocabulary: ' . \Drupal::entityTypeManager()->getStorage('taxonomy_vocabulary')->load($config['vocabulary'])->label()] : ['No vocabulary selected.']; }
方法创建用于词汇选择的UI:
settingsForm()
/** * {@inheritdoc} */ public function settingsForm($form, FormStateInterface $form_state) { $config = $this->getConfiguration(); $vocabularies = \Drupal::entityTypeManager()->getStorage('taxonomy_vocabulary')->loadMultiple(); $options = []; foreach ($vocabularies as $vocabulary) { $options[$vocabulary->id()] = $vocabulary->label(); } $form['vocabulary'] = [ '#type' => 'select', '#title' => $this->t('Vocabulary'), '#default_value' => $config['vocabulary'], '#options' => $options, ]; return $form; }
方法查询并呈现术语:
)根据所选格式处理术语格式。 记住要注入服务,而不是在生产环境中使用静态调用。build()
/** * {@inheritdoc} */ public function build() { $config = $this->getConfiguration(); if (!isset($config['vocabulary']) || !$config['vocabulary']) { return []; } $query = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->getQuery(); $query->condition('vid', $config['vocabulary']); $tids = $query->execute(); $terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadMultiple($tids); return [ '#theme' => 'item_list', '#items' => $this->buildTermList($terms), ]; }
buildTermList()
buildTermListItem()
结论
该综合指南演示了在Drupal 8中创建自定义DS字段,并展示了插件系统的功能和灵活性。 请记住在实施代码后清除缓存。 这种增强的方法为扩展显示套件功能提供了一种可靠且可维护的方法。
以上是Drupal 8中的自定义显示套件字段的详细内容。更多信息请关注PHP中文网其他相关文章!