Grav CMS — A way to pass URL parameters in a frontend form

tangled net
2 min readApr 7, 2022

--

Grav CMS allows developers to give third parties the ability to manage their (structured) content in a very elegant and flexible way. At the same time, there are few restrictions on how this content ends up displayed on the website — as long as the developer knows what he is doing.

Getting started with Grav is not particularly complicated and is well documented and possible without going deeper into the architecture by using Twig. Many things that would be difficult to do with WordPress are included in the standard tutorial. However, as soon as you reach certain limits, you need more know-how.

In one project I use Grav flex objects to display photographs similar to a shop system. In the detailed view of a photo, there should be a contact form to buy the selected motif as a poster. I used Grav to make everything as simple as possible — without a complicated store system that actually has too many features to pay for.

If someone wants to try it — there is (or was) apparently a possible solution to write a small PHP function: https://discourse.getgrav.org/t/form-field-set-by-url-parameter/5136/2

Unfortunately, it didn’t work for me.

Sounds like a simple task, but after a long time of trying and searching I ended up with the following approach in terms of effort/benefit:

On the form page, a short javascript recognizes the URL parameter and inserts it into a field with a certain ID.

My default-form.twig.html file at path user/plugin/form/templates/forms/layouts/form looks like this:

<form
{% block embed_form_core %}{% endblock %}
{% block embed_form_classes %}{% endblock %}
{% block embed_form_custom_attributes %}{% endblock %}
>
{% block embed_fields %}{% endblock %}
{% block embed_buttons %}{% endblock %}
<script>
const path = window.location.pathname;
document.getElementById('motif').value = decodeURI(path.match(/motif:(.*)/)[1]);
</script>

</form>

The page where the form template is located has an element with an ID motif.

title: ‘Motive Form’
form:
name: motive-form
... -
name: motif
label: ‘Motif Nr.’
type: text
id: motif
validate:
required: true

Simple solution, quick & dirty.

--

--

tangled net
tangled net

Written by tangled net

0 Followers

thoughts about ridiculously distant topics that go through my head

No responses yet