@Vadym said:
Make sure not to isolate the context with only in your {% include %} statement and watch out for page/form caching conflicts.
Make sure the variable value is properly passed (including if you're pulling values from the page header).
I've been using the "one form across multiple pages" along with the Automatic XHR Approach. I just tested rendering the same form multiple times inside a page template (not modular pages). While the submissions went through, XHR only worked on the first instance because both forms shared the same form.id.
One possible workaround is to override two form templates in your theme:
-
templates/forms/default/form.html.twig (in your theme) Add:
{% set base_form_id = form.id|default(form.name|hyphenize) %}
{% set dom_id = form_instance_id|default(base_form_id) %}
And replace form.id with dom_id on the wrapper and <form> attributes (lines 8 and 163)
-
templates/forms/layouts/xhr.html.twig (in your theme)
{% if form.xhr_submit == true %}
{% set base_form_id = form.id|default(form.name|hyphenize) %}
{% set target_form_id = form_instance_id|default(base_form_id) %}
{# Ensure xhr-submitter.js is loaded BEFORE the inline JS that uses it #}
{% do assets.addJs('plugin://form/assets/xhr-submitter.js', {'group': 'bottom', 'priority': 101, 'position': 'before'}) %}
{% do assets.addInlineJs("
document.addEventListener('DOMContentLoaded', () => {
if (typeof attachFormSubmitListener === 'function') {
attachFormSubmitListener('" ~ target_form_id|e('js') ~ "');
}
const formElement = document.getElementById('" ~ target_form_id|e('js') ~ "');
if (formElement && window.GravRecaptchaInitializers) {
const initializerFuncName = 'initRecaptcha_" ~ base_form_id|e('js') ~ "';
if (typeof window.GravRecaptchaInitializers[initializerFuncName] === 'function') {
// window.GravRecaptchaInitializers[initializerFuncName]();
}
}
});
", {'group': 'bottom', 'priority': 100, 'position': 'before'}) %}
{% do assets.addJs('plugin://form/assets/captcha/recaptcha-handler.js', {'group': 'bottom', 'priority': 99, 'position': 'before'}) %}
{% do assets.addJs('plugin://form/assets/captcha/turnstile-handler.js', {'group': 'bottom', 'priority': 98, 'position': 'before'}) %}
{# cap-handler.js is loaded by the cap field template itself so it works on non-XHR forms too. #}
{% endif %}
-
Implement your logic for assigning ID's.
{% include "forms/form.html.twig" with { form: forms('contact-form'), form_instance_id: 'contact-form-top' } %}
{% include "forms/form.html.twig" with { form: forms('contact-form'), form_instance_id: 'contact-form-bottom' } %}
I tested this setup and it works as expected for standard XHR submissions, though I haven't tested it with Turnstile or reCAPTCHA, you may also need to adjust recaptcha-handler.jsor turnstile-handler.js.Also take a look at plugin://form/assets/xhr-submitter.js (how sendFormData resolves form.id and wrapperId) in case you run into cases with multiple instances or re-renders.