Home >Backend Development >PHP Tutorial >Custom Display Suite Fields in Drupal 8

Custom Display Suite Fields in Drupal 8

Joseph Gordon-Levitt
Joseph Gordon-LevittOriginal
2025-02-16 12:04:09452browse

Display Suite: Mastering Custom Field Creation in Drupal 8

Display Suite (DS) remains a cornerstone of Drupal's contributed modules, offering robust tools for crafting site layouts and managing content presentation. Its strength lies in creating custom fields displayed alongside core field values within DS layouts. This capability, highly valued in Drupal 7, continues and expands in Drupal 8, leveraging the new object-oriented programming (OOP) architecture and plugin system. This guide details creating a custom DS field in Drupal 8.

Custom Display Suite Fields in Drupal 8

Drupal 8 Plugins and the DS Field Plugin Type

Drupal 8's plugin system replaces Drupal 7's _info hooks. DS utilizes this system, exposing a DsField plugin type. Instead of hook_ds_field_info(), we build a plugin class with metadata in its annotation and logic within its methods.

Creating the VocabularyTerms Plugin Class

Our example creates a DS field (within a custom module named "Demo") displaying taxonomy terms from a configurable vocabulary, limited to Article nodes. The plugin class (VocabularyTerms) resides in src/plugins/DsField and is annotated as follows:

<code class="language-php">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 {
}</code>

Default Configuration and Formatters

To allow vocabulary selection, we implement defaultConfiguration() to set a default vocabulary ("tags"):

<code class="language-php">/**
 * {@inheritdoc}
 */
public function defaultConfiguration() {
  return ['vocabulary' => 'tags'];
}</code>

Formatters (e.g., linked or unlinked term lists) are defined using the formatters() method:

<code class="language-php">/**
 * {@inheritdoc}
 */
public function formatters() {
  return ['linked' => 'Linked', 'unlinked' => 'Unlinked'];
}</code>

Custom Display Suite Fields in Drupal 8

Configuration Summary and Settings Form

The settingsSummary() method provides a UI summary of the selected configuration:

<code class="language-php">/**
 * {@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.'];
}</code>

Custom Display Suite Fields in Drupal 8

The settingsForm() method creates the UI for vocabulary selection:

<code class="language-php">/**
 * {@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;
}</code>

Custom Display Suite Fields in Drupal 8

Rendering the Field

The build() method queries and renders the terms:

<code class="language-php">/**
 * {@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),
  ];
}</code>

Helper methods (buildTermList() and buildTermListItem()) handle term formatting based on the selected formatter. Remember to inject services instead of using static calls in a production environment.

Custom Display Suite Fields in Drupal 8

Conclusion

This comprehensive guide demonstrates creating a custom DS field in Drupal 8, showcasing the power and flexibility of the plugin system. Remember to clear caches after implementing the code. This enhanced approach provides a robust and maintainable method for extending Display Suite functionality.

The above is the detailed content of Custom Display Suite Fields in Drupal 8. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn