How to use Drupal's plugin system for custom field widgets
Drupal’s Field API separates content storage, editing, and presentation. A field type defines the value, a field widget plugin supplies the form used to enter it, and a formatter renders it later. This separation lets teams improve editing controls without redesigning the underlying data model.
Developers usually encounter this architecture through Drupal’s plugin system. A widget is discovered by plugin type, selected for a compatible field in an entity form display, and instantiated when that form is built. The result is reusable across content types, bundles, and sites.
A practical Australian example is a phone-number field. Mobile-first communication is routine, yet contact forms must handle Melbourne’s 03, Brisbane’s 07, Perth’s 08, Canberra’s 02, and national mobile numbers beginning 04. A specialised widget can collect those choices consistently while keeping the stored value portable.
The same care applies to personal information. Under the Privacy Act 1988 and Australian Privacy Principles, a phone number can identify a person; consent and purpose should therefore be explicit. If the form triggers commercial SMS or email, the Spam Act 2003 creates separate obligations that the widget cannot satisfy by itself.
Understand the field widget layer
Drupal’s plugin manager scans enabled modules for classes carrying a field widget plugin attribute. It then compares each widget’s supported field types with the fields available on the content type being edited. Only compatible widgets appear in the field configuration interface.
Selecting a widget affects an entity form display rather than the field’s database definition. Editors can therefore use a guided widget on full node forms and another widget on inline forms without changing the field type or existing content. Widget-specific settings are stored with the relevant form display configuration.
A field widget should control input presentation, not output. If an editor needs a formatted phone number, link, swatch, or map on the published page, that belongs in a formatter plugin. Creating a custom field type is justified only when new storage semantics or schema are genuinely required.
Prepare the module and plugin contract
Start with a conventional Drupal module under web/modules/custom. The plugin class must follow Drupal’s namespaced directory structure so the plugin manager can discover it.
aus_contact_widget/
├── aus_contact_widget.info.yml
└── src/
└── Plugin/
└── Field/
└── FieldWidget/
└── AustralianPhoneWidget.php
The module metadata should state the Drupal versions supported by the implementation:
name: Australian Contact Widget
type: module
description: Provides a guided Australian phone-number field widget.
core_version_requirement: '^10.3 || ^11'
On Drupal 10.3 and Drupal 11, the plugin can use attributes. Extending WidgetBase provides the standard field-widget lifecycle, while FieldWidget declares the plugin identifier, translated label, supported field type, and configuration category.
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Plugin\Attribute\FieldWidget;
use Drupal\Core\StringTranslation\TranslatableMarkup;
#[FieldWidget(
id: 'aus_contact_widget_phone',
label: new TranslatableMarkup('Australian phone number'),
field_types: ['telephone'],
category: new TranslatableMarkup('Text'),
)]
final class AustralianPhoneWidget extends WidgetBase
{
}
The plugin identifier should remain stable once configuration has been exported. Renaming it can detach an existing form display from the intended widget and requires an accompanying configuration update.
Build an Australian phone widget
The widget targets Drupal’s core telephone field type and uses a fieldset containing an area selection and subscriber-number input. The area options cover the main Australian numbering prefixes without pretending that every suburb follows a simple state-based pattern.
Add these methods inside AustralianPhoneWidget:
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
public function formElement(FieldItemListInterface $items, $langcode): array
{
$stored = (string) ($items->value ?? '');
$element['value'] = [
'#type' => 'fieldset',
'#tree' => TRUE,
'#label' => $this->t('Australian phone number'),
'area' => [
'#type' => 'select',
'#title' => $this->t('Number prefix'),
'#options' => [
'04' => $this->t('Mobile (04)'),
'02' => $this->t('Canberra and NSW (02)'),
'03' => $this->t('Melbourne and Tasmania (03)'),
'07' => $this->t('Brisbane and Queensland (07)'),
'08' => $this->t('Perth, Adelaide and other 08 areas (08)'),
],
'#default_value' => $this->areaCode($stored),
'#required' => TRUE,
],
'number' => [
'#type' => 'textfield',
'#title' => $this->t('Subscriber number'),
'#default_value' => $this->subscriberNumber($stored),
'#maxlength' => 12,
'#required' => TRUE,
'#description' => $this->t('Enter the subscriber number only, without 02, 03, 04, 07 or 08.'),
],
];
return $element;
}
Because the control has several child inputs, massageFormValues() must reduce them to the single value expected by the field. International E.164 storage gives each number a predictable representation and avoids ambiguous spaces or punctuation.
public function massageFormValues(array $values, array $form, FormStateInterface $form_state): array
{
foreach ($values as $delta => $value) {
$input = $value['value'] ?? $value;
$area = $input['area'] ?? '';
$subscriber = preg_replace('/\D+/', '', $input['number'] ?? '');
if ($area !== '' && $subscriber !== '') {
$values[$delta]['value'] = '+61' . ltrim($area, '0') . $subscriber;
}
}
return $values;
}
The helper methods convert existing national and E.164 values into suitable defaults. They deliberately do not attempt to validate the complete Australian numbering plan.
private function areaCode(string $value): string
{
$digits = preg_replace('/\D+/', '', $value);
if (str_starts_with($digits, '61')) {
$digits = substr($digits, 2);
}
$digits = ltrim($digits, '0');
if ($digits === '') {
return '04';
}
$prefix = '0' . substr($digits, 0, 1);
return in_array($prefix, ['02', '03', '04', '07', '08'], TRUE)
? $prefix
: '';
}
private function subscriberNumber(string $value): string
{
$digits = preg_replace('/\D+/', '', $value);
if (str_starts_with($digits, '61')) {
$digits = substr($digits, 2);
}
$digits = ltrim($digits, '0');
return substr($digits, 1);
}
Add settings and protect stored data
Settings are optional, but they can make the widget more useful across an Australian organisation. A site administrator might choose the default prefix, enable landline options, or show an international-number notice. Implement settingsForm() to render those controls and settingsSummary() to explain the active configuration on the field management screen.
The widget’s transformations are not validation. The core telephone field accepts text and does not confirm that a prefix belongs to a particular exchange or that the subscriber number has a valid length. Add server-side validation using a field constraint, entity constraint, or a dedicated validation service based on current Australian numbering rules.
Keep stored values independent from translated labels. A value such as +61412345678 remains stable when an editor changes languages, while the option shown as “Mobile (04)” can be translated for another audience. This Australian-only widget should also avoid rewriting international numbers; sites serving overseas customers should provide a separate international option or field.
Treat submitted phone data as personal information even when it is not sent to a third party. Collect only what the workflow needs, avoid logging unnecessary values, and keep consent for marketing separate from the editing widget. Output escaping and link creation belong in a formatter, not in raw markup returned by the widget.
Test the widget in real editing workflows
Begin with manual checks covering empty values, existing national numbers, existing E.164 numbers, mobile and landline prefixes, long subscriber numbers, and invalid input. Include values relevant to Australian operations, such as a Melbourne number, a Brisbane mobile, a Perth landline, and an international number that the widget must leave untouched.
Check keyboard operation and screen-reader output. The fieldset needs a meaningful legend, each select and text input needs a visible label, and validation errors must be associated with the relevant control. If JavaScript formatting is added, keep the plain text field usable when scripts fail.
Translation testing should verify labels, help text, and summaries rather than stored values. If the widget later handles delivery windows or contact times, use identifiers such as Australia/Perth, Australia/Adelaide, and Australia/Sydney instead of ambiguous abbreviations. This matters around daylight-saving changes.
Automated coverage can include a kernel test for plugin discovery and form rendering, plus a functional test that submits the widget through a content form. Extracting number normalisation into a service also allows focused unit tests for prefix conversion, formatting, and rejected inputs.
Deploy and maintain the widget
Enable the module and rebuild Drupal’s caches so the plugin manager can discover the new class:
drush en aus_contact_widget -y
drush cr
Then select “Australian phone number” as the widget for the target telephone field. The choice can be made while editing the field or through the content type’s form-display settings. Export the updated configuration and import it in the target environment as part of the normal deployment process.
Switching to this widget changes future editing behaviour but does not rewrite values already stored. If existing records must be converted to E.164, perform that as a controlled data update with backups and verification. Widget code changes normally require a cache rebuild; configuration changes must also be exported.
Comparing the three extension points prevents unnecessary custom code:
| Concern | Field widget | Formatter | Field type |
|---|---|---|---|
| Primary purpose | Collects field input | Displays stored data | Defines storage semantics |
| Typical base class | WidgetBase |
FormatterBase |
FieldItemBase |
| Changes database schema | No | No | Usually yes |
| Configured through | Entity form display | Entity view display | Field type selection |
| Best suited to | Guided editing and input controls | Presentation and markup | New data structures |
The following practices keep the implementation dependable:
- Store canonical, machine-safe values and translate only visible labels.
- Keep normalisation separate from server-side validation and rejection rules.
- Limit personal-data collection and document where consent is captured.
- Test keyboard access, existing values, translations, and plugin discovery.
- Export configuration, rebuild caches, and avoid renaming published plugin identifiers.
This approach leaves the underlying field reusable while giving editors a focused Australian contact-number workflow across local development and production environments.