May 31, 2014

Applying a very simple template for theming a form

Drupal 8 uses Twig as its underlying theming engine, so there are some significant differences in how to apply template files for theming the forms that I've implemented and described in a previous post.

In this post I describe the changes I made to implement the use of a very simple template that in the D7 version contains no PHP except a call to drupal_render_children(). This post should serve as a very brief intro to the use of Twig and what changes are entailed.

First, as in D7, hook_theme needs to be implemented in the .modules file in order to define a hook, which in this case is implemented with a template file. The hook definition is essentially the same as in D7. The  path  property is not needed as long as the template file is placed in the  templates subdirectory under the module root.
function optimizely_theme($existing, $type, $theme, 
                          $path) {
  return array(

    'optimizely_account_settings_form' => array(
      'render element' => 'form',

        => 'optimizely-account-settings-form',

Second, the template file is named optimizely-account-settings-form.html.twig instead of optimizely-account-settings-form.tpl.php. Its contents are:
<p>In order to use this module, ... </p>
<p>Most of the configuration and ... </p>
{{ form }}
The last line is Twig syntax to print the contents of the variable form. The line replaces the following in the D7 version.
<?php echo drupal_render_children($form) ?>
Finally, the form array returned by the  buildForm method must have property  #theme  added but is otherwise the same as in D7.
public function buildForm(array $form,
                          array &$form_state) {
    = 'optimizely_account_settings_form';
  $settings_form['optimizely_id'] = array(
    '#type' => 'textfield',
    '#title' => $this->t('Optimizely ID Number'),
    // Other properties of the textfield ...
    = array('#type' => 'actions', );
  $settings_form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',

  return $settings_form;

DrupalTwig/sandwich  code repo
Example of using Twig theming engine, with the _content property in the routing file.

Twig best practices - preprocess functions and templates

No comments:

Post a Comment