localhostdotdev

Joined

10 Experience
0 Lessons Completed
0 Questions Solved

Activity

Posted in Dynamic Nested Forms with Stimulus JS Discussion

here is how I did it with asset pipeline and coffee script (adapted from your code)

class window.NestedFormController extends Stimulus.Controller
  @targets = ["links", "template"]

  add_association: (event) ->
    event.preventDefault()

    content = @templateTarget.innerHTML.replace(/NEW_RECORD/g, u.rand())
    @linksTarget.insertAdjacentHTML("beforebegin", content)

  remove_association: (event) ->
    event.preventDefault()

    wrapper = event.target.closest(".nested-fields")

    if wrapper.dataset.newRecord == "true"
      wrapper.remove()
    else
      wrapper.querySelector("input[name*='_destroy']").value = 1
      wrapper.style.display = "none"

window.application.register 'nested-form', window.NestedFormController