I'd like to use placeholders instead of labels for a form built with the form API.

I can get placeholders working well with the Elements module, but now I want to hide the labels. If I just set ['#title'] = NULL; then form errors don't have descriptive names, and it ruins accessibility.

In Drupal 7, you could set the #title_display to invisible (documentation). Was something like this backported in a contrib module somewhere?

Or is there a way I can set my own class on the label element?


Drupal 6 is a lot more limited than 7 or 8 in this regard, and I'm not aware of any effort to backport this functionality.

However, Drupal 7 and 8 use the .visually-hidden CSS class to hide the label, and it's not very hard to make Drupal 6 do the same.

It's possible to add classes to a form element label with a theme function, but I've found this hard work. A much easier approach is the use the #prefix and #suffix attributes to wrap the element in a div tag. For example:

$form['test'] => array(
  '#type' => 'textfield',
  '#title' => 'Test'
  '#prefix' => '<div class="hide-label">',
  '#suffix' => '</div>'

Then you just need to add the following CSS:

.hide-label label {
  position: absolute !important;
  clip: rect(1px,1px,1px,1px);
  overflow: hidden;
  height: 1px;
  width: 1px;
  word-wrap: normal;

The contents of this class are copied from Drupal 8's .visually-hidden.

Hope this solves your problem.



You could override the theme_form_element() function in your theme's template.php so that the label does not output:

// Remove  from output

function THEMENAME_form_element($element, $value) { // This is also used in the installer, pre-database setup. $t = get_t();

$output = '\n"; $required = !empty($element['#required']) ? '*' : '';

if (!empty($element['#title'])) { $title = $element['#title']; if (!empty($element['#id'])) { $output .= $t('!title: !required', array('!title' => filter_xss_admin($title), '!required' => $required)); } else { $output .= '$t('!title: !required', array('!title' => filter_xss_admin($title), '!required' => $required)); } }

$output .= " $value\n";

if (!empty($element['#description'])) { $output .= ' ' . $element['#description'] . "\n"; }

$output .= "\n";

return $output; }

Alternatively, you could target the form id > label and set it to display:none without modifying the theme function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.