Emmanu
Emmanu

Reputation: 797

How to integrate a copy button to a form that is created using cocoon gem

There are FundApplication and ExpenseRequest, FundApplication has_many expense_requests.

enter image description here

Pressing the 'Add Expense' Button will add expense requests and is working fine. Now my client asks me to implement a copy button here

enter image description here

What he wants is to add a button that inserts a new expense request but copy's the expense request's data the button belongs into the fields of newly created expense_request

I tried How to create a copy of item added in cocoon nsted form rails? How could I clone a child object in Rails using cocoon?

None of them worked for my scenario.

Upvotes: 0

Views: 111

Answers (1)

Cassandra S.
Cassandra S.

Reputation: 770

You have access to cocoon-specific callbacks; in particular, cocoon:after-insert. You can do something like this (untested):

$(document).ready(function() {
  $("#formContainer").on(
    "cocoon:after-insert", (event, insertedItem, originalEvent) {
      console.log("event: ", event)
      console.log("insertedItem: ", insertedItem)
      console.log("originalEvent: ", originalEvent)
  })
})

Using the original event (the click event) you can find the fields belonging to that button and get the values from that, and use those values to set the values in the newly inserted item.

Upvotes: 1

Related Questions