I use Grav for a while now for simple projets, I really love it ! I am now building a landing page for a future application to be developped, I want to integrate a form that sends data to a REST API, but input names get prefixed with data[]. I would like inputs’ names to be exactly what I define in my Frontmatter (eg. an hidden input with name: api_key would generate <input type=“hidden” name=“api_key”… instead of name=“data[api_key]”)
How can I achieve this without messing with source code ?
@davidbrisebois I haven’t tested if there are any side-effects and whether the forms still works, but the following steps will change the name attribute for your fields.
To change the name attribute, you could try something like the following:
Copy the file ‘/user/plugins/form/templates/forms/default/field.html.twig’ into your own template’s folder ‘/user/themes/mytheme/templates/forms/default/’
Change line 56:
// from
name="{{ (scope ~ field.name)|fieldName }}"
// into
{% if field.isAPI %}
name="{{ field.name }}"
{% else %}
name="{{ (scope ~ field.name)|fieldName }}"
{% endif %}
In the frontmatter of your form add the property ‘isAPI: true’ to your fields. Like:
fields:
myfield:
type: text
label: 'My Field'
isAPI: true
Thanks to the magic of Grav and a bit of ‘out-of-the-box’ thinking…
As said, I haven’t tested the behaviour of changing the field name, but I suspect it will work.
Thanks, but so far it is not working… seems like the field.html.twig is never loaded from my theme… I have flushed cache, force-refreshed my browser, nothing different. I also modified to name=“fuierfgnijng” but I still see name=“data[api_key]”
@jhabdas I understand there is a reason for Grav, but what’s the point to be able to customize action URL so I can send form to a third-party service, without being able to force input names to be the one that service requires (no control over it of course).
@davidbrisebois Are you sure the partial ‘field.html.twig’ is in the correct folder of your theme? It should be ‘/user/themes/mytheme/templates/forms/default/field.html.twig’.
I have double checked my sample in a newly created theme and it works as expected.
Yes I am sure ! I did it once more also to be very sure. Appi theme includes a field.html.twig in /user/themes/appi/templates/forms/field.html.twig I also tried changing it and nothing better…
I must say also that I tried to simply prepend name attribute with some random characters like name=“jghsrehyt{{ (scope ~ field.name)|fieldName }}” (without your solution) and still no random characters in generated source code.