Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

WTF: How do I get Drupal to put placeholder text inside my textfield?

What's that feature: the #attributes key.

Perhaps you have written your own javascript code to determine that an empty textfield does not have focus, and in such a situation place some placeholder text in the field. If you are using the FAPI there is an easier way. You can do this:

$form['my_textfield'] = array(
  '#type' => 'textfield',
  '#attributes' => array(
    'placeholder' => t('My placeholder text'),
  ),
);

Take note that this is telling Drupal to use the placeholder="My placeholder text" attribute for the textfield. The placeholder attribute is an HTML5 attribute. Keep this in mind when considering what browsers will be accessing your site and whether it's important for all visitors to see the placeholder text.

You can tell Drupal to use any (valid) HTML attributes with this technique.

This really-easy-to-use feature was one that I had forgotten about. So, I figured others may have forgotten about it as well. I hope you enjoy it!

Author: 
Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web