I have cocoon working with nested form, if you click add field link it inserts input fields. How do I render first input automatically, and then insert additional inputs when "add field" is clicked ?
In your controller, use this code. In the code below, jobs is a model and profile accepts_nested_attributes_for jobs. Replace @profile with whatever your form is for. The 2nd line is what will build the form fields, unless form fields already exist.
def new
@profile = current_user.profile
1.times {@profile.jobs.build} unless current_user.profile.jobs.any?
end
You may need to change times to time since its singular. In fact, you may be able to get rid of the times method altogether and do:
def new
@profile = current_user.profile
@profile.jobs.build unless current_user.profile.jobs.any?
end
The quick and dirty solution is to just use jQuery (which Cocoon requires anyways) to click Cocoon's "add item" button when the page loads:
$(document).ready(function() { $(".add_fields").click() } );
I use this in my "new" views, but not in "edit" views, since there may already be some nested items and I don't want to make assumptions. But you could also use script to count the nested item forms and conditionally show the "new item" fields.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With