how to add dynamic fields using ruby on rails and stimulus js?


I'm wanting to make a nested form in rails, with fronted in stimulus js. In the case a Provider can have many contacts, then in the Supplier form I must add a button that allows adding inputs to load Contacts as many times as I want.


    <div data-controller="provider">
        <div class="field" data-target="field">
                <%= f.fields_for :contacts do |builder| %>
                    <%= render 'contact_fields', f: builder %>
                <% end %>
                <button data-action="click->provider#addContact">
                     <%= link_to_add_fields( 'Add Contact', f,:contacts, class: 'btn btn-primary')  %>


      <%= f.check_box :_destroy%>
      <%= f.label :name %>
      <%= f.text_field :name %>

provider model

    class Provider < ApplicationRecord
        has_many :contacts, dependent: :destroy
        accepts_nested_attributes_for :contacts, allow_destroy: true

contact model

    class Contact < ApplicationRecord
         belongs_to :provider, optional: true


    import Rails from 'rails-ujs';
    import $ from 'jquery';
    import { Controller } from 'stimulus'

    export default class extends Controller {

        static targets = [ "fields", "form", "link" ]

        addContact(event) {
            var time = new Date().getTime()
            var regexp = new RegExp($(this).data('id'), 'g')
            $(this).before($(this).data('fields').replace(regexp, time))


When you want to add the nested form to the chrome console you see the following error:

    Error invoking action "click->provider#addContact"

    TypeError: Cannot read property 'replace' of undefined
        at Controller.addContact (provider_controller.js:14)
        at Binding../node_modules/@stimulus/core/dist/src/binding.js.Binding.invokeWithEvent (binding.js:52)
        at Binding../node_modules/@stimulus/core/dist/src/binding.js.Binding.handleEvent (binding.js:29)
        at EventListener../node_modules/@stimulus/core/dist/src/event_listener.js.EventListener.handleEvent (event_listener.js:28)

    {identifier: "provider", controller: Controller, element: div, index: 0, event: MouseEvent}

I based on the following example which is completely on ruby on rails

asked by sandovalgus 27.12.2018 в 00:32

0 answers