8000 Form auto‐fill with URL query parameters · mathspp/mathspp Wiki · GitHub
[go: up one dir, main page]

Skip to content

Form auto‐fill with URL query parameters

Rodrigo Girão Serrão edited this page Apr 14, 2025 · 4 revisions

I can link to a page with a form and it will auto-fill the form based on query parameters passed to the URL. For example, adding ?name=Rodrigo to the URL will find a form input for the name and pre-fill it with the value “Rodrigo”.

This works by using the following JS script:

document.addEventListener("DOMContentLoaded", () => {
    const urlParams = new URLSearchParams(window.location.search);

    for (const [key, value] of urlParams.entries()) {
        const selector = `form [name="data[${key}]"]`;
        const field = document.querySelector(selector);
        if (field) {
            field.value = value;
        }
    }
});

This was added as a standalone script auto_fill_form.js in my theme js folder and I modified the template forms/default/form.html.twig in the plugin form to include this script.

This also works for dropdown lists, but in that case the query parameter value must be set to the HTML option value, not the readable string that is shown to the user. E.g., in the testimonials form, instead of ?object=lightning%20 I would need to link to ?object=conference-lt to provide a testimonial for a lightning talk.

This does not seem to work if the URL also contains an anchor. Some initial debugging seemed to suggest that, in that case, window.location.search was empty.

Clone this wiki locally
0