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

时间:2019-03-27 07:32:25

标签: drupal drupal-8

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

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

对于form_custom.html.twig下的modulename/templates/,我具有以下内容:

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

该表单已呈现,但是它没有显示<h1>值TEST,也没有显示<form>标记内的自定义类“ mu-subscription-form”。

1 个答案:

答案 0 :(得分:1)

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

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

或者,您可以使用_form_set_attributes()

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