Home > Software design >  Cocoon Gem is rendering form twice
Cocoon Gem is rendering form twice

Time:11-13

I am using Cocoon Gem to build dynamic form. Every thing is working fine. I am able to add new record, delete the records. But my form and submit button is getting displayed twice. I have checked application.html.erb layout file and I haven't added coccon in my Layout file.

The way I added coccon gem is I added gem coccon in Gemfile and then I added coccon using yarn yarn add @nathanvda/cocoon and added following line in application.js file

require("jquery")
require("@nathanvda/cocoon")

My form view looks like below (this is the form which is getting displayed twice)

<%= form_with model: @user do |f| %>
  <%= f.fields_for :work_experiences do |work_experience| %>
    <div id='work_experiences'>
       <%= render "work_experience_fields", f: work_experience %>
    </div>
    <%= link_to_add_association 'add more work experience', f, :work_experiences, data: { association_insertion_node: '#work_experiences', association_insertion_method: :append } %>
            
    <%= f.submit 'Update Work Experience' %>
  <% end %>
<% end %>

My partial _work_experience_fields looks like below:

  <%= f.label :job_tile, 'Job Title'  %>
  <%= f.text_field :job_title, placeholder: 'Enter Job Title' %>
  <%= f.label :company_name, 'Company Name'  %> 
  <%= f.text_field :company_name, placeholder: 'Enter Company Name' %>
  <%= link_to_remove_association "remove task", f %>

Please help me debug why my form is displayed twice.

CodePudding user response:

Your Form should look like this: Basically, you need to close the fields_for loop.

<%= form_with model: @user do |f| %>
    <div id='work_experiences'>
       <%= f.fields_for :work_experiences do |work_experience| %>
          <%= render "work_experience_fields", f: work_experience %>
       <%end%>
   </div>
   <%= link_to_add_association 'add more work experience', f, 
       :work_experiences, data: { association_insertion_node: 
    '#work_experiences', association_insertion_method: :append } %>
        
  <%= f.submit 'Update Work Experience' %>
   
  <% end %>
  • Related