stimulus-components / stimulus-components

A modern Stimulus library delivering common JavaScript behaviors with a bunch of customizable controllers.
https://www.stimulus-components.com/
MIT License
1.08k stars 30 forks source link

Stimulus nested form expanded by default #62

Closed spacerobotTR closed 1 year ago

spacerobotTR commented 1 year ago

Instead of launching the nested form by pushing a button, is there a way to have it expanded with one record ready to go at first, then push the add button to add more form rows after that?

seanbjornsson commented 1 year ago

I accomplished this by making the following two updates (here outlined using the examples in the docs)


# in view, add `@user.todos` into the fields_for form. I did this also to make sure the 
# instances were attached to the nested form builder so I could access them later.
  <%= f.fields_for :todos, @user.todos do |todo_fields| %>
    <%= render "todo_form", f: todo_fields %>
  <% end %>

# In the controller, pre-populate an associated object (in this case a todo). Here in the edit/update route because
# that's what's in the docs, but I was using it in new/create as well.
class UsersController < ApplicationController
  def new
    @user = User.new
    @user.todos.build
  end
  # ...
  # Existing controller code in docs
end
guillaumebriday commented 1 year ago

I think the solution from @seanbjornsson is the correct way to do it 👍