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
logo Created with Sketch.

Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more. Icons by Icons8

© 2022 GoRails, LLC. All rights reserved.