TransWikia.com

Form API placeholder attribute rendered as "- Select -"

Drupal Answers Asked by hotwebmatter on December 24, 2020

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?

One Answer

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.

Correct answer by anonymous on December 24, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP