I have a custom form built with Form API that I am trying to add a class to on the form tag.

In the buildForm method, I have:

$form['#attributes']['class'][] = 'hl__single-input-form__form';

But the class doesn't appear on the form tag. Instead, the class appears on the div wrapper for the block that outputs the form.

In the block, the build method has:

   * {@inheritdoc}
  public function build() {
    return $this->formBuilder->getForm('\Drupal\harlib_newsletter_signup\Form\NewsletterSignup');

The only way I have been able to solve this is with a custom twig file with the following:

<section class="hl__single-input-form">
  <form{{ attributes.addClass('hl__single-input-form__form') }}>
    {{ children }}

But the twig shouldn't be necessary. I also notice that the form id as a css class also goes on the block wrapper, too. What is happening here?

1 Answer 1


Obviously the block plugin thinks the #attributes key in the returned array is meant for the block wrapper. So I would try to put the form in a subkey, this should prevent that the block plugin can access the attributes of the form:

  return ['form' => $this->formBuilder->getForm(...)];

By the way the core search block is also returning the form array directly like you did in the question and indeed, the resulting form tag in the search block has no classes too. I'm not sure, but this seems to be the same issue.

  • Yep, that fixed it.
    – Kevin
    Dec 5, 2017 at 15:17

Your Answer

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

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