Twig in form yaml, dynamic input values


I’m trying to make a contact form which would have one (or more) form fields pre-filled with values from page’s frontmatter from which the visitor came to it. I’m not sure if this is understandable, so I’ll try to demonstrate that on an example:

page1 with title: green would have a button, that would lead to the form page, when the visitor clicks that button, the form page opens with several contact form fields and some that would somehow get the information from the frontmatter of page1 (for eg. its title - green).

I thought that it would be possible to do quite easily, if twig functioned in the form definitons in yaml, but unfortunately it doesn’t work for me.

Is there a way how to do that easily, that I am not able to see?

Thanks in advance!

I’ve not tried it but it might be possible if you add this to the form.html.twig before the form include is called:

{% do form.setAllData(page.header.predefined_fields) %}

Where that predefined_fields had the name of the form field and the appropriate predefined value.

Gave this a quick test and it works! Here’s my test:

markdown file:

title: Predefined Form Fields

    name: predefined-form
            label: Name
            placeholder: 'Enter your name'
            autofocus: true
            autocomplete: true
            type: text
                required: true

            label: Website
            placeholder: 'Do you have a website?'
            type: text
                rule: url
                required: false

            type: submit
            value: Submit
        message: 'Thank you from your submission!'

    name: Bill Smith

And here’s my Twig:

{% extends 'partials/base.html.twig' %}

{% block content %}

    {% set submitted_data = %}

    {% set merged_data = page.header.predefined_fields|merge(submitted_data) %}

    {% do form.setAllData(merged_data) %}

    {% include "forms/form.html.twig"  %}

{% endblock %}

Thanks for this solution and prompt reply!

I’ve combined it with getting the page title from the uri param, that I’ve added to the link to the form page and it works perfectly!

<a href="{{ base_url }}/form/page:{{ page.header.title }}">...
{% set predefined_field =  {'page': uri.param('page')} %}