I created a custom field with the following definition:

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

    $value = isset($items[$delta]->value) ? $items[$delta]->value : '';

    $element += [
      '#type' => 'select',
      '#title' => $this->t('Select item'),
      '#options' => [
        'empty' => $this->t('Select an item'),
        'key1' => $this->t('value1'),
        'key2' => $this->t('value2'),
        'key3' => $this->t('value3'),
      '#suffix' => '<div class="custom-field-widget"></div>',
      '#attributes' => ['class' => ['edit-custom-field-widget']],
      '#attached' => [
        'library' => [

    return ['value' => $element];

In Formatter class I wrote this:

  public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = [];

    foreach ($items as $delta => $item) {
        $elements[$delta] = [
          '#type' => 'html_tag',
          '#tag' => 'p',
          '#value' => $item->value,
    return $elements;

When I show content type item with my custom field I see

"key1" but I would like to see: "value1"

Is it possible to show "value1" directly or are other operations necessary?


For the select Form element, the array key is the value, and the array value is the display of the option. That's why you're getting 'key1' for example.
If you want to achieve your goal you can write it this way:

'#options' => [
    'empty' => $this->t('Select an item'),
    $this->t('value1')->render() => $this->t('value1'),
    $this->t('value1')->render() => $this->t('value2'),
    $this->t('value1')->render() => $this->t('value3'),

Although this doesn't seem right :D
Also, while you're at it, you should check 'Select' form element documentation as you shouldn't add 'empty' value but rather use the '#empty_value'and '#empty_options' properties.

  • maybe you do not need your change, in the documentation I read this: #options: "An associative array, where the keys are the values for each option, and the values are the option labels to be shown in the drop-down list" My doubt now concerns the table on the db where the labels are stored, always if they are stored – Alessio Frabotta Sep 10 '18 at 12:52
  • 1
    I don't fully understand your comment. However, the labels are not stored in the database, only the values. In your case, the labels are stored in the translation because of the t() function – Ismail Cherri Sep 10 '18 at 12:56
  • this answer is enough for me :) I am a beginner with Drupal and so I have many doubts that are trivial for the most experienced people – Alessio Frabotta Sep 10 '18 at 13:03
  • You can mark it then as the accepted answer – Ismail Cherri Sep 10 '18 at 13:07

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.