Skip to content
● Meet Grav Guard: keep every Grav site you run secure and up to date, all from one place. Free for up to 3 sites. Read more →

can I create a form in a twig template?

Solved by Vadym View solution

Started by Anna 1 week ago · 5 replies · 185 views
1 week ago

I have a website that offers workshops with varying topics and dates. I would like each listing to have a quick sign up/show interest form underneath, just one input for an email address and a submit button. I can write this form in the page header in expert mode of course, but I have all the information I need saved in various other fields already.

So I wonder if there’s a way to generate this form automatically for each workshop. Just writing the thing in twig is easy, of course, but I don’t know how to hook that up to the forms plugin. Can that be done?

The other option I see is to write a plugin that adds the yaml in the header whenever the page is saved. Doable, but I hope there’s a neater way.

Thank you for your time and ideas!

1 week ago Solution

@Netzhexe, first, you can define a single form and include it across all pages (directly in your template):

TWIG
{%- set form_name = page.header.form_name|defined('contact-form') -%} {# leave an option to override it on page level #}
{% include "forms/form.html.twig" with { form: forms( form_name ) } %}

You can also pass variables from Twig or page.header into the form by using a hidden field with the evaluate: true parameter:

TWIG
{% include "forms/form.html.twig" with { form: forms( form_name ), 'my_var': my_var } %}
YAML
forms:
    contact-form:
        xhr_submit: true
        fields:
            url:
                label: 'Page'
                type: hidden
                evaluate: true
                default: page.url(true)
            id:
                label: 'Course ID'
                type: hidden
                evaluate: true
                default: header.id # page.header.id
            var:
                label: 'My Variable'
                type: hidden
                evaluate: true
                default: my_var
...

Make sure not to isolate the context with only in your {% include %} statement and watch out for page/form caching conflicts.

1 reply
1 week ago

Oh, perfect! I hadn’t thought of the trick with adding a variable to the form in twig, that’s exactly what I needed. Thank you!

6 days ago

@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:

  1. templates/forms/default/form.html.twig (in your theme) Add:

    TWIG
    {% 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)

  2. templates/forms/layouts/xhr.html.twig (in your theme)

    TWIG
    
    {% 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 %}
    
    
  3. Implement your logic for assigning ID's.

    TWIG
    
    {% 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.

❤️ 1
6 days ago

Got that sorted – it works all right, my xhr request was not working properly so the form got sent the page reloading way, and that apparently doesn’t use the unique form id that actually exists.

😕 1

Suggested topics

Topic Participants Replies Views Activity
Forms & Blueprints · by Anna, 2 days ago
2 51 15 hours ago
Forms & Blueprints · by Anna, 3 days ago
7 81 15 hours ago
Forms & Blueprints · by TomW, 1 month ago
3 377 1 month ago
Forms & Blueprints · by Japhy, 2 months ago
2 593 2 months ago
Forms & Blueprints · by FrViPofm, 2 months ago
5 623 2 months ago