5

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 ?

Bryan Ash
  • 4,385
  • 3
  • 41
  • 57
alexndm
  • 2,899
  • 5
  • 24
  • 25

2 Answers2

7

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
Philip7899
  • 4,599
  • 4
  • 55
  • 114
  • Thanks. In profile controller - 1.times {@profile.jobs.tasks} gives me undefined method `tasks' for # – alexndm Nov 11 '13 at 01:09
1

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.

wrydere
  • 668
  • 8
  • 17