Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render one association automatically with cocoon

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 ?

like image 516
alexndm Avatar asked Nov 10 '13 16:11

alexndm


Video Answer


2 Answers

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
like image 72
Philip7899 Avatar answered Oct 05 '22 22:10

Philip7899


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.

like image 39
wrydere Avatar answered Oct 06 '22 00:10

wrydere