Drupal 8:如何在表单标签中添加 class

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

如何在自定义表单的表单属性中添加 class?类似于以下内容:

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

我创建了一个自定义模块并在 /src/Form/ 中创建了一个名为 CustomForm.php 的表单。下面是 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);
    }

  }

}

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',
    ),
  );
}

我在 modulename/templates/ 下的 form_custom.html.twig 有以下内容:

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

表单已呈现,但它不显示 <h1> 值 TEST,也不显示 <form> 标记内的自定义 class "mu-subscription-form"。

表单渲染元素是 drupal“可渲染数组”的子集,它与父元素的工作方式相同 <form> 与其他元素的工作方式相同:

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

或者您可以使用 _form_set_attributes() :

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