0

There's a div called .description in a form in the site I've inherited. I want to add a another class to the div.

The div's content is created within hook_form_FORM_ID_alter(), eg:

$form['#description'] = 'Please enter your full name';

I've tried adding a classed to it like:

$form['#description'] = [
    '#markup' => '<div class="my-class">Please enter your full name</div>',
  ];

But this just results in "Array" being printed.

Would anyone know what I could do add a class to this element?

2
  • Why did you add an 's' in the second example? #description is not an element, its the description text - in this case it would be for the form itself. Does that text appear at the top of the form and not attached to anything?
    – Kevin
    Nov 20, 2017 at 0:34
  • @Kevin, oops typo. The text appears at the bottom of the form, but still within the form element, wrapped in it's own div <div class="description">Please enter your full name</a>. (I don't know where the description class is coming from.)
    – MeltingDog
    Nov 20, 2017 at 0:36

1 Answer 1

0

That's not what you want. What you want to do is add it to the form structure like this:

$form['#attributes']['class'][] = 'my-class';

Since you didn't list an element on the form, I can only assume you want the class on the form itself. If you want to wrap an element with a div with a class on it, you can do:

$form['element']['#prefix'] = '<div class="my-class">';
$form['element']['#suffix'] = '</div>';

That will wrap the entire element.

3
  • Thanks, yes this adds the class to the wrapping <form> element, but I want to target the div element within that form element.
    – MeltingDog
    Nov 20, 2017 at 0:38
  • That comes from the core theming function theme_form_element: cgit.drupalcode.org/drupal/tree/includes/form.inc?h=7.x#n4261 it is hardcoded there. To get around that, you would need to change the theme wrapper for this element to point to a custom one or add JS to add the class on (not preferable). I am not sure if there is a contrib module to help this, I don't know of one off the top of my head.
    – Kevin
    Nov 20, 2017 at 0:43
  • Barring any overrides of this theming function, this div will appear for any element that has a #description key.
    – Kevin
    Nov 20, 2017 at 0:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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