1

In a custom Drupal 8 module, I have a couple of Form API fields of '#type' => 'select':

    $form['form-right']['field_role'] = [
      '#type' => 'select',
      '#title' => $this->t('Role'),
      '#title_display' => 'invisible',
      '#required' => TRUE,
      '#options' => [
        'foo' => $this->t('Role Foo'),
        'bar' => $this->t('Role Bar'),
        'baz' => $this->t('Role Baz'),
        'quux' => $this->t('Role Quux'),
        'plugh' => $this->t('Role Plugh'),
        'xyzzy' => $this->t('Role Xyzzy'),
      ],
      '#attributes' => [
        'placeholder' => $this->t('Role'),
      ],
    ];

    $form['form-right']['field_contact_reason'] = [
      '#type' => 'select',
      '#title' => $this->t('Contact Reason'),
      '#title_display' => 'invisible',
      '#required' => TRUE,
      '#options' => [
        'foo' => $this->t('Contact Reason Foo'),
        'bar' => $this->t('Contact Reason Bar'),
        'baz' => $this->t('Contact Reason Baz'),
        'other' => $this->t('Other'),
      ],
      '#attributes' => [
        'placeholder' => $this->t('Contact Reason'),
      ],
    ];

Before a value is selected, the dropdown select picklists display the string '- Select -':

Form API placeholder attribute rendered as "- Select -"

The client would like them to display the value in the placeholder attribute instead.

Have I done something wrong?

1
  • Does the - Select - thing happen on all browsers?
    – leymannx
    Sep 19, 2020 at 17:36

1 Answer 1

5

According to the documentation: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element%21Select.php/class/Select

#empty_option: (optional) The label to show for the first default option. By default, the label is automatically set to "- Select -" for a required field and "- None -" for an optional field.

1
  • Thanks, that was it! Sep 19, 2020 at 18:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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