Drupal 8 views html5 text placeholder

You are here

In Drupal 8 views an anonymous user has the ability to filter content. When exposes the filters is enabled. But there is no html5 placeholder by default for a text field. The function below will add placeholder text to every views exposed form input as long it has a label.

/**
 * Implements hook_form_alter().
 *
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 * @param $form_id
 */
function _form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if($form_id == "views_exposed_form"){
    $keyFromForm = key($form['#info']);
    if (isset($keyFromForm)) {
      $exposedValue = $form['#info'][$keyFromForm]['label'];
      $exposedKey = $form['#info'][$keyFromForm]['value'];
      $form[$exposedKey]['#attributes']['placeholder'] = t( $exposedValue);
    }
  }
}