【问题标题】:Drupal 8 module - How to use a template to display a form element?Drupal 8 模块 - 如何使用模板显示表单元素?
【发布时间】:2016-12-22 21:53:12
【问题描述】:

我目前正在创建一个 Drupal 8 模块。我希望能够使用自定义模板在表单中显示 select 元素。这是我目前写的代码:

文件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.

如果我从$form['color'] 中删除'#theme' =&gt; 'colorselector',它会正确显示表单,但它显然不使用我的模板。

你知道错误来自哪里以及如何解决它吗?

谢谢!

【问题讨论】:

    标签: drupal twig drupal-8


    【解决方案1】:

    你的 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-07
      • 2017-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多