in this link https://api.drupal.org/api/drupal/modules!field!field.api.php/function/hook_field_widget_form_alter/7

it describes that we can add css class to an element in a form via this code

function hook_field_widget_form_alter(&$element, &$form_state, $context) {
  // Add a css class to widget form elements for all fields of type mytype.
  if ($context['field']['type'] == 'mytype') {
    // Be sure not to overwrite existing attributes.
    $element['#attributes']['class'][] = 'myclass';

I tried to use it but it seems $element['#attributes']['class'][] = 'myclass'; doesn't add any css class to form after rendering.

So how can I add css class to a form element inside hook_field_widget_form_alter() ?

  • you should use the development module to find out with $element you have to use – Josh Oct 6 '15 at 10:29

Old issue but it might help future viewers. Try this: $element['value']['#attributes']['class'] = 'myclass';

See field_multiple_value_form() which creates the render array. Then main theme function for rendering fields in forms is theme_field_multiple_value_form() and the parent theme function is theme_form_element()

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.