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?

Started by Anna 20 hours ago · 1 replies · 34 views
20 hours 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!

14 hours ago

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

Suggested topics

Topic Participants Replies Views Activity
Forms & Blueprints · by TomW, 1 month ago
3 334 4 weeks ago
Forms & Blueprints · by Japhy, 2 months ago
2 560 1 month ago
Forms & Blueprints · by FrViPofm, 2 months ago
5 571 2 months ago
Forms & Blueprints · by Ton Haarmans, 6 years ago
13 2559 9 months ago
Forms & Blueprints · by Hugo Oliveira, 10 months ago
0 990 10 months ago