Skip to main content

Drupal 8: Add placeholder attribute to an input form element

Adding placeholder text to a Drupal 8 form element that is the label of the form can be done in your .theme file with the hook template_preprocess_input().

  1. /**
  2.  * Implements template_preprocess_input().
  3.  */
  4. function MYTHEME_preprocess_input(&$variables) {
  5.   // Set a placeholder for all search form elements.
  6.   if ($variables['attributes']['type'] == 'search') {
  7.     $variables['attributes']['placeholder'] = $variables['element']['#title']; 
  8.   }
  9. }

The code above will add the #title of the form field as a placeholder attribute to any field of type 'search'.


Comments