如何将复制按钮集成到使用 cocoon gem 创建的表单中

问题描述

有 FundApplication 和 ExpenseRequest,FundApplication 有_许多费用_requests。

enter image description here

按“添加费用”按钮将添加费用请求并且工作正常。现在我的客户要求我在这里实现一个复制按钮

enter image description here

他想要的是添加一个按钮,插入一个新的费用请求,但将按钮所属的费用请求的数据复制到新创建的费用请求的字段中

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

它们都不适用于我的场景。

解决方法

您可以访问特定于 cocoon 的回调;特别是,cocoon:after-insert。你可以做这样的事情(未经测试):

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

使用原始事件(click 事件),您可以找到属于该按钮的字段并从中获取值,然后使用这些值在新插入的项目中设置值。