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:

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:

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.

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”.

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

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:

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:

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

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.
- WRITTEN BY:Merlin Sánchez
- POSTED ON:6/1/2016
- TAGS:Drupal 8 Custom Field Custom Module