logo
Submitted by Mikhail Ismajlov on Tue, 10/01/2019 - 12:18

In this tutorial we will look at how the Field Widget of the Link module works. This is a review article, so if you want to start writing your File Widget, please skip to the following articles.

In the last lesson we added Link fields for nodes and blocks. Now let's look at what the form for the Link field is formed by.

We have already met with autoloading of PHP classes in Drupal 8, and there is also a WidgetBase field widget class for fields:

core/lib/Drupal/Core/Field/WidgetBase.php

By creating a new child class in the module and putting it in the src/Plugin/Field/FieldWidget, the class will automatically connect and it can be used for the field. Let's look at the widget class for the Link field:

core/modules/link/src/Plugin/Field/FieldWidget/LinkWidget.php

The class annotation contains the field type to which this widget can be used:

/**
 * Plugin implementation of the 'link' widget.
 *
 * @FieldWidget(
 *   id = "link_default",
 *   label = @Translation("Link"),
 *   field_types = {
 *     "link"
 *   }
 * )
 */

In this way you can add new field widgets to the custom module for existing fields.

Let's now move on to the formElement() method, which is probably one of the main widget methods, where form elements are added via the Form API. There are three elements in the Link widget:

$element['title']
$element['uri']
$element['attributes']
These fields will then be used to enter data on a node or block form. Validation is also added to the fields because, for example, the URI field must contain the correct URL or local site address.

Also one of the important methods of settingsForm(), it is responsible for the form of customization that you can see on the Manage form page:

link

All other methods in the Field Widget are optional. We won't go into detail about each of the methods because they are not necessarily used to write custom modules. If you will write contributor modules, I think you won't find it difficult to read the description of the parent class methods:

core/lib/Drupal/Core/Field/WidgetBase.php

All Field Widgets for fields are configured on the Manage form display tab for each bundle entity separately:

manage form display