Skip to main content
Image
Network

Rendering a form in a Twig template

In this article, we will build a very basic form; It is a list (select) of cities, which we want to render in a template to adjust very particular styles and functionality through js .

We must start by creating the form. To do this and as always in Drupal 8, we have to start from a modular structure, that is, we have to do all this from the basic structure of a custom module; You can see what the structure of a custom module is like here . We will locate the form in my_module/src/Form/MyForm.php

In the MyForm.php class we will highlight the buildForm() method, where we will build the form.

public function buildForm(array $form, FormStateInterface $form_state) {  
  $form['cities'] = [  
    '#type' => 'select',  
    '#options' => cities[...],  
  ];   
  $form['#attached']['library'][] = 'my_module/cityvalues';  
  
  return parent::buildForm($form, $form_state);  
}

We also have to declare the js file in our my_module.libraries.yml as follows:

cityvalues:
  js:
    js/cityvalues.js: {}
  dependencies:
    - core/jquery

The next step is to create the custom block, which will be responsible for loading the form previously created through the template.

public function build() {  
  $form = \Drupal::formBuilder()->getForm('Drupal\my_module\Form\MyForm');
    
  return [  
    '#theme' => 'block_cities',  
    '#city_form' => $form,  
  ];
}

As you can see, first we instantiate the form in the $form variable . Then in the array that we return, we call the id of the twig template (which will be 'cities_template') and we will pass the form to it in a variable. Now we will use our my_module.module to use the hook_theme.

function my_module_theme() {  
  return [  
    'block_cities' => [  
      'template' => 'block--cities',  
      'variables' => [  
        'city_form' => NULL,  
      ],
    ],
  ];
}

This hook will be responsible for identifying the 'block_cities' id with the name of the template assigned to it (block–cities.html.twig), in addition to setting the 'city_form' variable that it will receive later, which will contain the instantiated form. The last step is to create the twig template, respecting the my_module/templates/block–cities.html.twig directory

And we must not forget that we also attach a js to this form, which we will locate in my_module/js/cityvalues.js

In this way, every time we place the custom block somewhere on our portal, we will be calling a form that will go through a custom template and load a js with a specific functionality. I hope it has been useful to you and that you have learned something new, that is the most important thing!

Tags

Join the Drupal Sapiens Community

Save content that interests you, connect with others in the community, contribute to win prizes and much more.

Login or create an account here

Latest posts

Featured

Last news