Dynamic Form Options With Hotwire Turbo Frames

I needed a way to dynamically show and hide form options based on what a user selects and wanted to use Turbo Frames. The benefit being all of the logic can be in the erb file of what to show and hide based on the current state of the model.

This works by calling a Stimulus controller posting the unsaved form to your controller and reloading the frame the form is in. The stimulus controller adds a hidden form value to tell the controller to use mode.attrbutes = instead of update so the changes are not saved in the database and then edit action is render again and reloaded into the form frame.

I attempted to create screencast to show the method I used to do this. I would consider it a beta since it’s my first attempt at a screencast :slight_smile:. I’m also using a similar method to add/delete items from a nested has many releationship which I will do a screencast on as well if anyone finds this first one helpful.

Watch Screencast
View Sample Code

4 Likes

What’s interesting is the no new routes and controller actions need to be added. Just the same form, and the same route. very interesting.

Hi Joe,

Would you be able to elaborate on what the subaction_id element is doing?

I use the subaction_id if I need to pass an object id to the subaction. For example if I’m deleting something from a has_many/nested list.

Just wanted to add that this video shows an even better method, which doesn’t refresh the whole page