How to create a field type in Drupal 8

Problem

Sometimes we have to resolve a specific functionality in our projects. This blog was created in respond to this problem of custom fields. The following part describes the main aspects of a custom field and shows the code. 

First step: Create a new module:

Image
d1

The directory structure of a module looks like as follow:

For more information about how to create a custom module follow the next link https://www.drupal.org/node/2560405    

Second step: Creating a custom field type:

Field types define the properties' fields and how they are stored in the database. 

Create a new PHP file called CustomFieldFieldType.php into FieldType folder and paste the following code:

Image
d7

The keywords "namespace" and "use" are very important for the functionality. In you take a look at line #9 it starts the annotation code; here we define the ID of the custom field; The label shows the selected item and the description is only used to described something about your new custom field type; In the default widget you set the ID from the default widget then you need to set a formatter type ID in the default formatter.      

On the other hand, on the line #20 you have to create a class “CustomFieldFieldType” that extends FieldItemBase. 

Image
d3

 

The function called “propertyDefinitions” defines all the properties about the field, in this case it sets the label and requirement as well as,  the data type of the field “string”.

 

Image
d4

The "schema" function defines how the field is stored into the database and the attributes that it has defined.  

Image
d5

The "isEmpty" function defines what to do if the field is empty.

Third step: Creating a custom field formatter:

Create a new PHP file called "CustomFieldFormatterType.php" into FieldFormatter folder and paste the following code:

Image
d6

FieldType is necessary to define the "namespace", "uses" and "annotation"; then you can define a class “CustomFieldFormatterType” that it extends from FormatterBase class.
The function viewElments defines the formatter that display the field by the users. 

Fourth step: Creating a custom field widget:

Create a new php file called CustomFieldWidgetType.php into the FieldWidget folder and paste the following code:

Image
d7

FormatterType is necessary to define the namespace, uses and annotation. Now create a class “CustomFieldWidgetType” that extends from WidgetBase

Image
d8

The function "formElement" defines the way that the editor shows users and gets the new values to save or update the field values.

That's all you need!... Congratulations! You have a created new custom field type in Drupal 8.