Nested multi-step (wizard) form

I have been building an app that has two models, Address and Review. I want to create a multi-step (wizard) form that is split into three parts, all on separate, subsequent pages. The first page contains the input fields for the Address model, the second and third page contains input fields for the Review model. I know the two concepts are separately possible (nested forms on their own, and multi-step forms on their own), is it possible to combine the two to get what I'm looking for? Can anybody point me in the right direction? Thanks in advance. Dan

Posted over 4 years ago by Dan Tidmas
Posted over 4 years ago by Alex Yang

Hey Dan, one way you could approach this is to think of it as two separate forms:
1) A single-page Address form
2) A two-page Review form

If you already know how to build each form individually, then you only need to link the two. For example, the 'Next page' link at the bottom of the first form could be used to save the Address fields to the database and if successful, direct the user to the first page of the Review form. Does that make sense?

The way to implement this would be to modify the 'create' action of your Address controller. You'll need to make sure that at the bottom, when the fields are saved successfully, the 'redirect_to' takes the user to the Review form. From the user's perspective, it should appear pretty seamless as long as you've wired it up correctly.

Let me know if you have any questions - hope that helps!

Posted over 4 years ago by Dan Tidmas

Thanks for the advice Alex, that should do nicely as a solution to start with. The only limitation I'm finding is that the user can't then go back from the first page of the review form to the address form - as it's already been submitted.

I eventually want to make this into an AJAX form too, I've heard that's not too hard a thing to do, even with little knowledge.

Thanks again for the help so far, after trying PLENTY of tutorials, yours has me almost up and running! Very excited!

Posted over 4 years ago by Alex Yang

Thanks for the kind words - I'm glad you've found the content useful!

A way to solve the 'back' button issue for the review form is to set the default value of the field to be:
1) the previously submitted value (retrieved from the database)
2) blank if no value has been submitted yet

If you use this approach, your input field could look something like this:
<%= f.number_field :product_id, value: ( || "") %>

Here, I'm using the 'value' parameter to set a default value for the field. The default value is either set to the existing stored value from the database or to an empty string. If you've set up validations, you'll be able to make sure that the form will be rejected if the user tries to submit with an empty string.