'Drupal 8: how can I add a class in form tag

How can I add a class in the form attribute within a custom form? Similar to the below:

<form class="mu-subscription-form"></form>

I have created a custom module and within the /src/Form/, created a form named CustomForm.php. Below is the CustomForm.php:

namespace Drupal\custom\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Class CustomForm.
 */
class CustomForm extends FormBase {


  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'custom_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['name'] = [
      '#type' => 'textfield',
      #'#title' => $this->t('name'),
      '#weight' => '0',
    ];
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
      '#attributes' => array('class' => array('mu-readmore-btn')),
    ];

    $form['#theme'] = 'custom';

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Display result.
    foreach ($form_state->getValues() as $key => $value) {
      drupal_set_message($key . ': ' . $value);
    }

  }

}

And I have the following content for the custom.module:

/**
 * Implements hook_theme().
 */
function custom_theme() {
  /*return [
    'custom' => [
      'render element' => 'children',
    ],
  ];*/
  return array(
    'form__custom_form' => array(
      'render element' => 'form',
      'template' => 'form_custom',
    ),
  );
}

I have the below content for the form_custom.html.twig under modulename/templates/:

<h1>TEST</h1>
<form{{ element }} class="mu-subscription-form"></form>

The form is rendered however, it is not displaying the <h1> value TEST nor showing the custom class "mu-subscription-form" within the <form> tag.



Solution 1:[1]

Form render elements are a subset of drupal "renderable arrays", it works the same with the parent <form> as it works with other elements :

$form['#attributes']['class'][] = 'mu-subscription-form';

Alternatively you can use _form_set_attributes() :

_form_set_attributes($form, ['mu-subscription-form']);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1