🇬🇧
Drupal Documentation and Guides
Guides
English
English
  • Getting Started with Drupal
  • Installing Drupal
  • Drush
  • Theme & Module Development Concepts
  • Modules
  • Themes
  • FrontEnd
    • Javascript
  • Backend
    • Helpful Drupal Classes and Methods
    • Entities
    • Nodes
    • Taxonomies
    • Hooks
    • Twig
    • Libraries
    • Queries
    • Forms
    • Files & Images
    • Helpful functions and solutions
  • Guides
    • Custom Fields
      • Entity Reference and integer
      • Two Text Fields
      • Textfields, formatted text and numbers
      • Links and media elements
Powered by GitBook
On this page
  • FieldType
  • FieldWidget
  • FieldFormatter
  1. Guides
  2. Custom Fields

Two Text Fields

A group of two textfields

In this example will be creating a field that has both an entity reference field and an integer field.

FieldType

The FieldType is the class that will handle the storage of the field. It will be responsible for storing the data in the database and retrieving it. It will also be responsible for validating the data.

<?php

namespace Drupal\MODULE_NAME\Plugin\Field\FieldType;

use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\TypedData\DataDefinition;

/**
 * @FieldType(
 *   id = "YOUR_FIELD_TYPE_ID",
 *   label = @Translation("THE LABEL THAT WILL BE DISPLAYED"),
 *   description = @Translation("A SIMPLE DESCRIPTION OF THE FIELD"),
 *   category = @Translation("THE CATEGORY WHERE IT WILL BE DISPLAYED"),
 *   default_widget = "YOUR_DEFAULT_WIDGET",
 *   default_formatter = "YOUR_DEFAULT_FORMATTER",
 * )
 */
// Simple example of a custom field type of two text fields
class FieldTypeName extends FieldItemBase {

  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties['FIELD_ONE'] = DataDefinition::create('string')
                                                   ->setLabel(t('NAME OF THE FIELD'));

    $properties['FIELD_TWO'] = DataDefinition::create('string')
                                                          ->setLabel(t('NAME OF THE FIELD'));

    return $properties;
  }

  public static function schema(FieldStorageDefinitionInterface $field_definition) {
    return [
      'columns' => [
        // Schema for a normal text field
        'FIELD_ONE'        => [
          'type'     => 'text',
          'size'     => 'tiny',
          'not null' => FALSE,
        ],
        // Schema for a normal text field
        'FIELD_TWO' => [
          'type'     => 'text',
          'size'     => 'tiny',
          'not null' => FALSE,
        ],
      ],
    ];
  }

  public function isEmpty() {
    if (!empty($this->FIELD_ONE) || !empty($this->FIELD_TWO)) {
      return FALSE;
    }

    return TRUE;
  }

}

FieldWidget

The FieldWidget is the class that will handle the display of the field in the form. It will be responsible for displaying the field in the form and handling the data that is sent from the form.

<?php

namespace Drupal\MODULE_NAME\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * @FieldWidget(
 *   id = "YOUR_DEFAULT_WIDGET",
 *   label = @Translation("THE LABEL THAT WILL BE DISPLAYED"),
 *   description = @Translation("A SIMPLE DESCRIPTION OF THE FIELD"),
 *   field_types = {
 *     "YOUR_FIELD_TYPE_ID"
 *   }
 * )
 */
class FieldWidgetName extends WidgetBase  {

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {

    $element['FIELD_ONE'] = [
      '#title'  => $this->t('FIELD ONE'),
      '#type'   => 'textfield',
      '#default_value' => isset( $items[ $delta ] ) ? $items[ $delta ]->FIELD_ONE : NULL,
      '#weight' => 10,
    ];

    $element['FIELD_TWO'] = [
      '#title'  => $this->t('FIELD TWO'),
      '#type'   => 'textfield',
      '#default_value' => isset( $items[ $delta ] ) ? $items[ $delta ]->FIELD_TWO : NULL,
      '#weight' => 10,
    ];

    return $element;
  }

}

FieldFormatter

The FieldFormatter is the class that will handle the display of the field in the view. It will be responsible for displaying the field in the view.

<?php

namespace Drupal\MODULE_NAME\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;

/**
 * @FieldWidget(
 *   id = "YOUR_DEFAULT_WIDGET",
 *   label = @Translation("THE LABEL THAT WILL BE DISPLAYED"),
 *   description = @Translation("A SIMPLE DESCRIPTION OF THE FIELD"),
 *   field_types = {
 *     "YOUR_FIELD_TYPE_ID"
 *   }
 * )
 */
class FieldFormatterName extends FormatterBase {

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = [];

    foreach ($items as $delta => $item) {
      // The text value has no text format assigned to it, so the user input
      // should equal the output, including newlines.
      $elements[$delta] = [
        '#type' => 'inline_template',
        '#template' => '{{ value|nl2br }}',
        '#context' => ['value' => $item->value],
      ];
    }

    return $elements;
  }

}
PreviousEntity Reference and integerNextTextfields, formatted text and numbers

Last updated 2 years ago