Back to Top

Add placeholder text to Views Exposed Filter

I see this question pop up all the time, it's probably a good candidate for a module, but until then here is a simple way to add 'placeholder' text to an exposed form in Drupal Views.

Add this snippet to your template.php file:

/**
* Implements hook_form_alter().
*/
function lantra_awards_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == "views_exposed_form"){
    if (isset($form[&;full_text_search&;])) {
            $form[&;full_text_search&;][&;&;] = array(&;placeholder&; => array(t(&;Enter a search term&;)));
    }
  }
}

Make the following changes:
Replace 'hook' in hook_form_alter with your theme name.
Replace 'full_text_search' on both lines with the name of your form.
Replace 'Enter a search term' with the text you want displayed on the form.

Save your template.php file, flush the cache and be happy with a job well done.

So what did we just do?
Well the meat of the function is really in that last line, is a HTML 5 form value, and one of it's parameters is 'placeholder'. Here we have given the parameter value of the form we're displaying the string 'Enter a search term', we also used Drupal's 't' function which is best practice when working in Drupal and allows for content translation.

Further reading:

FAQ:
I don't have a template.php file, where is it?

It's usually located in your theme folder, most themes have one, but if not you can create one or even put this snippet in a custom module.

My template file already has a form_alter function it it, can I still add this?
It's better if you add this snippet to the pre-existing function, just add the following lines:

  if($form_id == "views_exposed_form"){
    if (isset($form[&;full_text_search&;])) {
            $form[&;full_text_search&;][&;&;] = array(&;placeholder&; => array(t(&;Enter a search term&;)));
    }
  }

Is there anything that will break if I do this?
Some browsers don't support HTML 5 so that will need to be checked, also it might break views where the search string is saved.