Drupal 8 module - How to use a template to display a form element?
<p>I'm currently creating a Drupal 8 module. I would like to be able to use a custom template to display a <code>select</code> element in a form. Here is the code I have written so far:</p>

<p>File <code>my_module/templates/colorselector.html.twig</code>:</p>

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

  &lt;script&gt;
    $('.color-selector').colorselector();
  &lt;/script&gt;
{% endspaceless %}
</code></pre>

<p>File <code>my_module/my_module.module</code>:</p>

<pre class="lang-php prettyprint-override"><code>use Drupal\Core\Render\Element;
use Drupal\Core\Render\Element\RenderElement;

function my_module_theme($existing, $type, $theme, $path) {
    return [
        // ...
        'colorselector' =&gt; [
            'render element' =&gt; 'select'
        ]
    ];
}

function my_module_preprocess_colorselector(&amp;$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 =&gt; $colorCode) {
        $option = [];
        $option['value'] = $colorName;
        $option['label'] = $colorName;
        $option['code'] = $colorCode;
        $variables['options'][] = $option;
    }
}
</code></pre>

<p>File <code>my_module/src/Form/MyCustomForm.php</code>:</p>

<pre class="lang-php prettyprint-override"><code>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' =&gt; 'select',
            '#theme' =&gt; 'colorselector',
            '#title' =&gt; $this-&gt;t('Couleur'),
            '#required' =&gt; TRUE,
            '#options' =&gt; $options
        ];
        // ...
        return $form;
    }

    // ...
}
</code></pre>

<p>I get the following error message when I try to display the form: <code>The website encountered an unexpected error. Please try again later.</code></p>

<p>If I remove <code>'#theme' =&gt; 'colorselector'</code> from <code>$form['color']</code>, it displays the form correctly but it does not use my template obviously.</p>

<p>Do you know where the error comes from and how to fix it?</p>

<p>Thanks!</p>