Theme colour switcher

How to make core search block form label visible - Drupal 8

By default, the label for the core Search module text input in Drupal 8 is invisible, that is, it's present but visually hidden so users of assistive technology can read it. But what if you want to display it visually?

There's no way to do it through configuration, and little to no information about how to do it with code. I found where the visibility was being set, in SearchBlockForm.php in the core Search module.

$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.')],

I first created a form alter function to set the title display to visible, but that removed it completely. I finally figured it out: the label visibility isn't a Boolean with values of visible or invisible. Rather, the label is 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' ) {

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



You are my hero for figuring this out. Thank you!

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.