Twig in form yaml, dynamic input values

Hi,

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!
AB

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

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

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

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


predefined_fields:
    name: Bill Smith
---

And here’s my Twig:

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

{% block content %}

    {% set submitted_data = form.data.toArray %}

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

    {% do form.setAllData(merged_data) %}


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

{% endblock %}
3 Likes

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')} %}
...