Skip to main content

Error message on custom drupal field widget

From time to time I stumble upon the following error message when creating a custom field type in drupal 8: "This value should be of the correct primitive type.". It occurs when I try to enable the field on a content type and is caused by the widget ... I can't even save the widget settings form.

Each time I have to search for the error - while perfectly knowing, that I already found the solution some time before ... so that's why I'm writing it here once and for all:

When creating the field widget with drupal console it produces output like this:

public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $element['value'] = $element + [
      '#type' => 'textfield',
      ...
    ];

    return $element;
  }

Simply remove the $element + before the returning form element to solve this issue ...

public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $element['value'] = [
      '#type' => 'textfield',
      ...
    ];

    return $element;
  }