Custom field in Drupal 8
Blog

How to Create Custom field in Drupal 8 (Part -1)

In a recent project we had to create a section that is having range  with the select list for the unit. It had to be usable in different sections of the layout and work the same. For this we came up with a pretty nifty (we think) solution of creating a custom field that solved this particular problem for us. I will walk you through how to create a custom field/widget/formatter for Drupal 8. There are Drupal console commands for generating boilerplate code for this…

To Create Custom field we need to create 

  1. Field Type
  2. Field Widget
  3. Field Formatter


This is the folder structure for creating the same

Temperature Range

  • temperature_range.info.yml
  • src/
    • Plugin/
      • Field/
        • FieldType/
          • TemperatureRangeItem.php
        • FieldFormatter/
          • TemperatureRangeFormatter.php
        • FieldWidget
          • TemperatureRangeWidget.php

Field Type creation
First, we need to create our own custom module, we can use drupal console for creating new module, then 

The namespace of that class should be \Drupal\MODULE_NAME\Plugin\Field\FieldType
In our example \Drupal\temperature_range\Plugin\Field\FieldType\BazItem

To create a field type, you need a class with the FieldType annotation.

The annotation above the class, within the doc comment, should include a unique id, and a label.

Then provide a schema for the field. This will be the properties that we have created above.

Then provide the field item’s properties and this will be the properties which we created

In the forthcoming blog, we will see how to create field widget and field formatter which both will complete the custom field creation

Download the Drupal Guide
Enter your email address to receive the guide.
get in touch