Nested form in a table, not working

308 views Asked by At

Can someone help me on how I will put my nested form in a table?

my code:

#app/view/master_templates/edit.html.erb
<%= form_for(@master_template) do |f| %>     
  <%= f.label :name %><br />
  <%= f.text_field :name %>

  <table border="1">
    <%= f.fields_for :master_template_details, :wrapper => false do |p| %>
      <%= render 'master_template_detail_fields', {f: p} %>
    <% end %>
    <tr><td><%= link_to_add_fields "Add Details", f, :master_template_details %></td></tr>
  </table>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

#app/views/master_templates/_master_template_details_fields.html.erb
<tr class="fieldset">
  <td><%= f.hidden_field :id %></td>
  <td><%= f.select :field_type_id, options_from_collection_for_select(FieldType.all, :id, :name, f.object.field_type_id) %></td>
  <td><%= f.hidden_field :_destroy %></td>
  <td><%= link_to "Remove Detail", '#', class: "remove_fields" %></td>
</tr>

#app/helpers/application_helper.rb.
  def link_to_add_fields(name, f, association)
    new_object = f.object.send(association).klass.new
    id = new_object.object_id
    fields = f.fields_for(association, new_object, child_index: id) do |builder|
        render(association.to_s.singularize + "_fields", f: builder)
    end
    link_to(name, '#', class: "add_fields btn", data: {id: id, fields: fields.gsub("\n", "")})
  end

#app/assets/application.js.coffee
jQuery ->
  # Remove fieldset
  $('form').on 'click', '.remove_fields', (event) ->
    $(this).prev('input[type=hidden]').val('true')
    $(this).closest('fieldset').hide()
    event.preventDefault()

  # Add more fieldset
  $('form').on 'click', '.add_fields', (event) ->
    time = new Date().getTime()
    regexp = new RegExp($(this).data('id'), 'g')
    $(this).before($(this).data('fields').replace(regexp, time))
    event.preventDefault()

When I tried to click Add Details link, it will create <fieldset>*details*</fieldset> inside <td> of Add Details link. And the Remove Detail link is not working, but without the table it is working.

I found this, but it is not working or I am doing it wrong. I am a noob in nested, ROR, and js. Please help in details. Thanks

1

There are 1 answers

3
bunty On BEST ANSWER

try with if its working.. I am not pretty sure.

$('form').on 'click', '.remove_fields', (event) ->
$(this).parent().prev().find('input[type=hidden]').val('true')
$(this).parent().parent().hide()
event.preventDefault()


$('form').on 'click', '.add_fields', (event) ->
time = new Date().getTime()
regexp = new RegExp($(this).data('id'), 'g')
$(this).parent().parent().before($(this).data('fields').replace(regexp, time))
event.preventDefault()