Building a custom widget for fieldsfor Drupal 8 , 9 , 10 , and 11

Last updated :  

A field widget is the translator between what a database column can store and what a human can comfortably type. The field_example_rgb field type from the last lesson stores one thing — a hex color string like #a1b2c3 — but almost nobody wants to type six hex digits by hand. This lesson builds a widget that splits that single value into three friendlier Red/Green/Blue text boxes, then reassembles them back into one hex string on save.

What you'll learn in this lesson

  • The @FieldWidget annotation and its required field_types property
  • How formElement() builds the actual input controls a user sees
  • Using #element_validate to parse and reassemble a composite value

The @FieldWidget annotation

/**
 * Plugin implementation of the 'field_example_3text' widget.
 *
 * @FieldWidget(
 *   id = "field_example_3text",
 *   module = "field_example",
 *   label = @Translation("RGB text field"),
 *   field_types = {
 *     "field_example_rgb"
 *   }
 * )
 */
class Text3Widget extends WidgetBase {

The field_types array is what makes a widget appear as an option (or not) when a site builder is choosing how a specific field should be edited — this widget declares compatibility with exactly one field type, but a more general-purpose widget could list several.

formElement() — building the actual inputs

public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
  $value = $items[$delta]->value ?? '';
  if (!empty($value)) {
    preg_match_all('@..@', substr($value, 1), $match);
  }
  else {
    $match = [[]];
  }

  $element += [
    '#type' => 'details',
    '#element_validate' => [[$this, 'validate']],
  ];

  foreach (['r' => $this->t('Red'), 'g' => $this->t('Green'), 'b' => $this->t('Blue')] as $key => $title) {
    $element[$key] = [
      '#type' => 'textfield',
      '#title' => $title,
      '#size' => 2,
      '#default_value' => array_shift($match[0]),
      '#attributes' => ['class' => ['rgb-entry']],
    ];
  }
  return ['value' => $element];
}

The stored hex string (#a1b2c3) is split apart with a regular expression into three two-character chunks — one per textfield's default value — the moment the form renders. Each pair of hex digits becomes a separately editable box. This is the "friendlier input" half of the translation; the next method handles the return trip.

#element_validate — reassembling the value

public function validate($element, FormStateInterface $form_state) {
  $values = [];
  foreach (['r', 'g', 'b'] as $colorfield) {
    $values[$colorfield] = $element[$colorfield]['#value'];
    if (strlen($values[$colorfield]) == 0) {
      $form_state->setValueForElement($element, '');
      return;
    }
    if ((strlen($values[$colorfield]) != 2) || !ctype_xdigit($values[$colorfield])) {
      $form_state->setError($element[$colorfield], $form_state, $this->t("Saturation value must be a 2-digit hexadecimal value between 00 and ff."));
    }
  }
  $value = strtolower(sprintf('#%02s%02s%02s', $values['r'], $values['g'], $values['b']));
  $form_state->setValueForElement($element, $value);
}

This is where the reassembly happens: #element_validate runs during form validation, reads the three separate textfield values back out, validates that each is genuinely a 2-digit hex value, and — critically — calls $form_state->setValueForElement() to overwrite what gets saved with a single reassembled hex string. As far as the field type's schema() is concerned, only one value was ever submitted; the three-textbox experience is entirely the widget's doing.

Validation and reassembly happen in the same method here — that's a design choice, not a requirement. A more complex widget might use a separate #element_validate callback purely for validation and only reassemble the value in a submit handler. Combining them, as this widget does, is simplest when the reassembly logic and the validation logic depend on exactly the same data.

Quick check: if a user left the Green field empty but filled in Red and Blue, what would this widget actually save? (An empty string, not a partial hex value — the validate() method returns immediately with an empty value the moment any one of the three fields is empty, rather than trying to save a malformed color.)

Key takeaways

  • A Field Widget's job is purely presentational: translate one stored value into friendlier input controls, and translate the submitted input back into that same stored shape.
  • field_types in the @FieldWidget annotation controls which field types a widget is even offered for.
  • #element_validate is the standard place to both validate a composite widget's sub-values and reassemble them into the field's real stored format.
  • $form_state->setValueForElement() is how a widget overrides what actually gets saved, independent of what was literally submitted.

Coming up next

Input handled — the final piece of the field trio is display. Next you'll build a Field Formatter that turns this same stored hex value into a rendered color swatch.