Skip to main content

Drupal 8 - add theme suggestions with form ids

By default, there is only one theme form suggestion for every form. To change this use this snippet inside your .theme file:

function scriptun_theme_suggestions_form_alter(array &$suggestions, array $variables){
    $formId = $variables['element']['#id'] ?? null;
    if ($formId) {
        $suggestions[] = 'form__' . str_replace('-', '_', $formId);
    }
}

Change scriptun with your theme name, and check suggestions. Example debug for login form:

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'form' -->
<!-- FILE NAME SUGGESTIONS:
   * form--user-login-form.html.twig
   x form.html.twig
-->

You can remove -form suffix if you want:

function scriptun_theme_suggestions_form_alter(array &$suggestions, array $variables){
    $formId = $variables['element']['#id'] ?? null;
    if ($formId) {
        $suggestions[] = 'form__' . str_replace(['-', '_form'], ['_', ''], $formId);
    }
}

Suggestions should work anyway if you use dashes instead of underscores, but it's nice to keep Drupal naming convention

Add new comment

CAPTCHA

This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.

We use cookies on our website to enhance your user experience. We also use Google analytics and ads.

Click here to read more I've read it