AJAX form trap with reset action and emailing

Thought I’d share this knowledge, since I wasted a lot of time figuring it out. I only spotted the solution after I’d typed up a long question about it here. Should have tried the rubber ducky method much sooner :frowning:

I have never built a form using AJAX submit. I don’t generally like them as a user. This time I needed to use one for contact form on a “single page” site that uses modals. (urgh, SPA :face_vomiting:)

I want to spotlight that recently the Form plugin has been improved to make AJAX forms much simpler. Big :pray: thanks to @rhuk for making that happen.

I added actions to the form incrementally (save, message, reset). They seemed to work fine. (I had never needed reset but it seemed to make sense and I didn’t think much about it.)

Then I went to add emails, one for the site owner and a thank-you email for the sender. The form seemed to do nothing. I checked Grav’s logs and saw:

[CRITICAL] An email must have a "To", "Cc", or "Bcc" header.

By elimination I found that it was the email receipt for the sender that was causing the error, and specifically the recipient (set in my form action as "{{ form.value.email }}") was an empty string.

This is probably where better PHP debugging tools could have helped me. Unfortunately, I haven’t been able to connect to them since I started using Docker exclusively.

Hard-coding the address produced a working form. I checked the field value after submission and it was correct. It seemed the dynamic Twig value was not being passed or being incorrectly processed at some point. It seemed strange because other dynamic values from the form were being passed into the data file created by the save action.

Without giving every boring debug detail, I’ll post the solution next as a reply and mark it as the solution…

It turned out that the position of the reset action is critical. Moving it to the end of the form actions (initially it was at the top) did the trick. I guess the form values were reset before the email was processed.

I’m still not quite sure why the form values were correctly rendered in the saved data file, but I can appreciate that it’s probably minor differences in implementation that I can live without knowing everything about.

My final form actions were:

            - ip:
            - email:
                to: "{{ form.value.email }}"
            - email:
                to: "{{ config.plugins.email.to }}" # this always worked
            - save:
                body: "{% include 'forms/data.txt.twig' %}" # this always worked and contains form values
            - message: Thanks for getting in touch. You should see a receipt in your inbox. We'll get back to you soon.
            - reset: true

Hope that help someone.