Drupal 8模块 - 如何使用模板显示表单元素?

时间:2016-12-22 21:53:13

标签: drupal twig drupal-8

我目前正在创建一个Drupal 8模块。我希望能够使用自定义模板在表单中显示my_module/templates/colorselector.html.twig元素。这是我到目前为止编写的代码:

档案{% spaceless %} <div class="select-wrapper"> {% set classes = ['form-control', 'color-selector'] %} <select{{ attributes.addClass(classes) }}> {% for option in options %} <option value="{{ option.value }}" data-color="{{ option.code }}"{{ option.selected ? ' selected="selected"' }}>{{ option.label }}</option> {% endfor %} </select> </div> <script> $('.color-selector').colorselector(); </script> {% endspaceless %}

my_module/my_module.module

档案use Drupal\Core\Render\Element; use Drupal\Core\Render\Element\RenderElement; function my_module_theme($existing, $type, $theme, $path) { return [ // ... 'colorselector' => [ 'render element' => 'select' ] ]; } function my_module_preprocess_colorselector(&$variables) { $element = $variables['element']; Element::setAttributes($element, ['id', 'name', 'size']); RenderElement::setAttributes($element, ['form-select']); $variables['attributes'] = $element['#attributes']; $variables['options'] = []; foreach ($element['#options'] as $colorName => $colorCode) { $option = []; $option['value'] = $colorName; $option['label'] = $colorName; $option['code'] = $colorCode; $variables['options'][] = $option; } }

my_module/src/Form/MyCustomForm.php

档案namespace Drupal\my_module\Form; use Drupal\Core\Form\FormBase; use Drupal\Core\Form\FormStateInterface; class MyCustomForm extends FormBase { public function buildForm(array $form, FormStateInterface $form_state) { // ... $form['color'] = [ '#type' => 'select', '#theme' => 'colorselector', '#title' => $this->t('Couleur'), '#required' => TRUE, '#options' => $options ]; // ... return $form; } // ... }

The website encountered an unexpected error. Please try again later.

当我尝试显示表单时收到以下错误消息:'#theme' => 'colorselector'

如果我从$form['color']中移除SELECT max(PrimaryKeyID) MaxPrimaryKeyID, max(CreateDate) MaxCreateDate FROM VeryHeavyView WHERE Condtion < 123 SELECT PrimaryKeyID, ColA, ColB, ColC , CreateDate FROM VeryHeavyView WHERE Condtion < 123 ,它会正确显示表单但显然不会使用我的模板。

您知道错误的来源以及如何解决吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

你的hook_theme函数应该是这样的。

function my_module_theme($existing, $type, $theme, $path) {
  return array(
    'color_selector' => array(
      'variables' => array('params' => null),
      'template' => 'colorselector'
    )
  );
}

现在,您的模板名称可能是 my_module / templates / colorselector.html.twig