I created a content type with my own custom field as described in Why do I get this error when I save my custom field?

The insertion of an item with this content type works, but when I want to modify the article I verified that I lose my custom field setting (it's a select box).

What is the method to keep the setting?


According to the code in the mentioned question, you need to define #default_value property and assign the $value variable to it like this:

public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {

    $value = isset($items[$delta]->value) ? $items[$delta]->value : '';
    $client   = \Drupal::httpClient();
    $request = $client->get('http://localhost:8083/regionilist');
    $response = json_decode($request->getBody());

    $element += [
      '#type' => 'select',
      '#title' => $this->t('Select element'),
      '#options' => $response,
      '#suffix' => '<div class="custom-field-widget"></div>',
      '#attributes' => ['class' => ['edit-custom-field-widget']],
      '#attached' => [
        'library' => [
      '#default_value` => $value,

    return ['value' => $element];
| improve this answer | |
  • If I understand correctly the comments for the other answer, it should be json_decode($request->getBody(), TRUE). – kiamlaluno Sep 11 '18 at 13:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.