2016-12-22 3 views
0

В настоящее время я создаю модуль Drupal 8. Я хотел бы иметь возможность использовать собственный шаблон для отображения элемента select в форме. Вот код, который я написал до сих пор:Модуль 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'], он отобразит форму правильно, но не использует мой шаблон, очевидно.

Вы знаете, откуда исходит ошибка и как ее исправить?

Спасибо!

ответ

0

Ваша функция hook_theme должна быть такой.

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

Теперь ваше имя шаблона может быть my_module/шаблоны/colorselector.html.twig