On the “primary form” page, I have an “Add” button that navigates to another form page where the user can add “additional optional information”. When the “Add” button is clicked, I want to save the primary form input so that when the user returns from the “additional information” form to the primary form, all of the previous entered information on the “primary form” is restored.
When saving the form data as described above, I need a way to store this away “temporarily” so that it can be restored later. It cannot save partial/incomplete data to the database because the primary form data may be incomplete and have validation errors when the navigation occurs.
This feels like a pretty common pattern to me but I have not yet found a way to do this using Rails forms so I am looking for recommendations. If JavaScript is required, I would prefer to use Hotwire.
Thanks in advance for your help and recommendations.
In general you have 3 sensible directions. 2 front-end and 1 back-end.
Front-end: use modal popup for the second form, without going to a new page.
Front-end: store data in something like local storage.
Back-end: this is the safest route, with lowest risk of data loss for the user, and supports multiple devices. However, you have to do it all yourself: save partial data, implement multiple validation contexts (search “rails validation contexts”). There is no shortcut.
You could probably think of some hacks using session, flash, get params, or similar, but I would strongly advise against them.
I just did this for adding a new contact to a report form. report state is saved to local storage. contact form is loaded with return value because coming from another form and not from new contact form. contact is saved > return to report and select contact field is updated in report and filled.
Thank you for the quick replies. My initial take was to use local storage to pull this off. My hope was that there might be a gem or a bit of open source I could leverage to do this to avoid reinventing the wheel.
Going the local storage route, it should be possible to leverage Stimulus to do this.
I’ve found the issue with any of these type of save state in session/local storage is, when do you throw it away? Say you save the form details, then they completely bail on the flow. And do 10 “other” things in the app. Would you still expect that form to re-populate if/when they come back? Maybe, but also I’ve seen in a lot of cases where no you don’t. So how do you know it’s safe to throw away that save state then? I don’t have a good answer for this, just some food for thought.