0

When doing a preprocess on a page (I need to conditionally change something at the page template level) is there a way to tell if the page is going to render a form? The xdebug output didn't show any variables that would tell me this in an obvious way.

4
  • 1
    A page can't be a form. A page can contain a form. But we don't know how this form (what form?) got there. So, impossible to tell. You need to share more info/context. Maybe target the node ID or route name. – leymannx May 6 at 20:12
  • It could be many forms. Or any form. The login page, user registration, user editing, etc. This line exists in the page template: {% set container = theme.settings.fluid_container ? 'container-fluid' : 'container' %} so usually the container-fluid class is applied. But I don't like how it looks on forms, so I'd rather apply the container class. – shelane May 6 at 20:18
  • 1
    If your form is block, check existence of this block on the page. If it's in $page, check your URL. – Nikit May 7 at 1:03
  • As a rule of thumb, if Drupal preprocess functions doesnt gives you what you are looking for, it probably means that you are not preprocessing the appropriate element. And considering a form would be part of a region (region content?) this rule seems to be appropriate in your care. – Denis Kolmerschlag May 10 at 2:27
0

Since I wanted to apply a change to the page.html.twig template based on if it was a form, I looked first for the form suggestions I was given. Since I couldn't find a way to generically apply a template to all forms, I instead created a template that I would then tell all of the forms that I have to use this template. I used a hook_theme_suggestions_HOOK_alter to add my new template and check the existing suggestions to see if the forms I want to use are part of the current suggestions:

function listed_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  $forms = [
    'page__user__register',
    'page__admin__people',
  ];
  foreach ($forms as $form) {
    if (in_array($form, $suggestions)) {
      $suggestions[] = 'page__forms';
    }
  }
}

From here, I can add additional forms as they are needed to use this single template. So, this solution doesn't exactly answer my original question, but it solves my original problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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