Add css property for individual components in form elements - Drupal

Sparky picture Sparky · Feb 16, 2011 · Viewed 16.8k times · Source

I have a drupal form and I need to add separate classes to the components in a form element.

That is I need to add the attribute class='text' to the 'textbox (the actual box)' and class='title' to the 'textbox title' (#title').

How do I do this?

Answer

user113292 picture user113292 · Feb 16, 2011

For the first case—adding the class to the textfield itself—use the #attributes property:

$form['foo'] = array(
  '#type' => 'textfield',
  '#title' => t('Textbox title'),
  '#attributes' => array(
    'class' => array('text'), // change to just 'text' for Drupal 6
  ),
);

For the second case——adding the class to the label—you are out of luck with the Forms API. Instead, you could target it using the wrapper class for the field and label:

.form-item-field-foo label {
  /* CSS here */
}