You are here

How to make search block form label visible - Drupal 8

By default, the label for the search form text input in Drupal 8 is set to invisible, that is, it's present but hidden by applying the "visually-hidden" class so users of assistive technology can still read it. But what if you want to display it visually?

That's not so easy. There's no way to do it through configuration, and little to no information about how to do it with code.

I muddled around and finally found where the visibility was being set, in SearchBlockForm.php in the core Search module. In there we find:

$form['keys'] = [
      '#type' => 'search',
      '#title' => $this->t('Search'),
      '#title_display' => 'invisible',
      '#size' => 15,
      '#default_value' => '',
      '#attributes' => ['title' => $this->t('Enter the terms you wish to search for.')],
    ];

Based on that, in my theme's .theme file, I put a form alter function:

function mytheme_form_alter(&$form, $form_state, $form_id) {
  if ( $form['#form_id'] == 'search_block_form' ) {
    $form['keys']['#title_display'] = 'visible';
  }
}

Clear cache, win, right?

Nope. Label actually disappeared. Instead of being present but visually hidden, it vanished completely from the markup.

I finally figured it out: the label visibility isn't a Boolean in the sense of the values being visible or invisible. Rather, the label is by default visible unless it's set to invisible. So, we need to remove the #title_display attribute altogether:

function mytheme_form_alter(&$form, $form_state, $form_id) {
  if ( $form['#form_id'] == 'search_block_form' ) {
    unset($form['keys']['#title_display']);
  }
}

Presto, clear cache and the label shows up.

Normally you're not supposed to unset form elements, but this isn't an actual form element, just the visibility attribute for the label.

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.