0

I have a module that is building a form. I want to theme the form using twig within my module so it does not interfere with my theme/custom twigs.

My buildForm function is:

public function buildForm(array $form, FormStateInterface $form_state) {

  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => $this->t('Name'),
    '#title_display' => 'invisible',
    '#required' => TRUE,
  );

  $form['#theme'] = 'custom_form';

  return $form;
}

I have set the theme for the form as custom_form and it works fine using this in my .module file:

function custom_module_theme($existing, $type, $theme, $path) {
  return array(
    'custom_form' => array(
      'render element' => 'form',
    ),
    'input' => array(
      'template' => 'input',
      'render element' => 'element',
    ),
  );
}

However the input fields are still being rendered using input.html.twig file in my /theme/custom theme folder.

I have created copied the twig template file using the same name and placed it in my custom_module folder however Drupal is still using my theme input.html.twig file.

How do I override this twig and use the input.html.twig file in my custom_module templates folder?

Thanks

2
  • I don't think you can have a template that has the same name as another template outside of the context of overriding the former.
    – Kevin
    Commented Feb 1, 2017 at 22:25
  • Oh okay, how would I go about adding a custom twig template to theme the input fields?
    – harnamc
    Commented Feb 1, 2017 at 22:32

1 Answer 1

0

Found the answer after some intensive searching and looking at Drupal From API: Create a twig file for the theme, I called it custom-input.html.twig and place it in your custom_module templates folder. Then you tell Drupal about it using hook_theme() function:

function custom_module_theme($existing, $type, $theme, $path) {
  return array(
    'custom_input' => array(
      'render element' => 'element',
    ),
  );
}

Lastly, in the buildForm function you say what theme will render the element like below:

public function buildForm(array $form, FormStateInterface $form_state) {

  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => $this->t('Name'),
    '#title_display' => 'invisible',
    '#required' => TRUE,
    '#theme' => 'custom_input'
  );

  $form['#theme'] = 'custom_form';

  return $form;
}

This will tell Drupal to render the form input elements using the custom twig file you created.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.