顯示套件:掌握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中文網其他相關文章!