Drupal form placeholder attributes

Submitted by swim on Tue, 07/30/2013 - 04:02

Note, the original article was written some time ago. Since then a number of changes to the Drupal FAPI & Webform have been made. Webform now supports managed form placeholder attributes!

Adding placeholder attributes to forms implements a great html5 feature while in turn saving space & giving that 'modern' design look. Depending upon how you want to display your site's forms; features like hiding the original label or providing some additional styling to those form's inheriting placeholder attributes is almost always necessary. A fairly simple problem arrises if you attempt to hide form labels before render, e.g. in a form_alter. Suppose you apply your placeholder as such;


  $exclude = array('select', 'radios', 'checkboxes', 'managed_file');
  foreach ($form['submitted'] as $name => $component) {
    if (!in_array($component['#type'], $exclude) && $name != '#tree') {
       $form['submitted'][$name]['#attributes']['placeholder'] = $component['#title'];
       $form['submitted'][$name]['#title'] = '';
    }
  }

This solution will immediately start displaying issues if your form uses validation. The #title key must retain it's value for validation to function as normal; finding the required field upon submit.


  $exclude = array('select', 'radios', 'checkboxes', 'managed_file');
  foreach ($form['submitted'] as $name => $component) {
    if (!in_array($component['#type'], $exclude) && $name != '#tree') {
      $form['submitted'][$name]['#title_display'] = 'invisible';
      $form['submitted'][$name]['#attributes']['placeholder'] = $component['#title'];
    }
  }

Please note, the elements module is required for Drupal 7 as it includes required HTML5 attribute support. The above example is implemented using Webform.