verbb / formie

The most user-friendly forms plugin for Craft CMS.
Other
93 stars 69 forks source link

Retaining form values on submit (or remember/autofill)? #1817

Closed jishi closed 2 months ago

jishi commented 2 months ago

Question

I have a form which is supposed to be filled out multiple times with slightly changed values, and I would like to either retain the values on ajax submit, or if there are some convenient way to hook into the submit (so I can store it away in localStorage or similar) and then auto-populate it on load?

Additional context

No response

engram-design commented 2 months ago

If you wanted to retain all values in the form after submission, there's actually not a configuration setting for that as it's assumed almost everyone would want to do this. I can look at adding that.

But if you want to reset the form, but just have some fields populated, then your best bet is to use JS to pre-populate those values. But there's not a shortcut to getting field values, or setting them on fields, that would all be manual.

let $form = document.querySelector('form');

const formValues = {};

$form.addEventListener('onBeforeFormieSubmit', (e) => {
    const handle = 'test';
    const $field = $form.querySelector('[data-field-handle="' + handle + '"]');
    const value = $field.value;

    formValues[handle] = value;
});

$form.addEventListener('onAfterFormieSubmit', (e) => {
    let data = e.detail;

    // If the last page was submitted
    if (!data.nextPageId) {
        const handle = 'test';
        const $field = $form.querySelector('[data-field-handle="' + handle + '"]');

        $field.value = formValues[handle];
    }
});
jishi commented 2 months ago

I worked around this by storing the fields I wanted retained in the onBeforeFormieSubmit event, and then pre-poulated them on the DOMContentLoaded-event of the page. I couldn't find a formei event on when the formw as initialized that worked, but that could have been something specific to my setup.