Search code examples
javascriptjqueryruby-on-railscocoon-gem

Datepicker issue when using cocoon Gem with Materialise Css and simple form in ruby on rails 5 app


I am using Cocoon gem for nested forms in my Rails app. I'm using it alongside materialize-form gem which allows me to use materialize css alongside simple form.

In the materialize-form gem notes it gives a solution to using nested form using the nested forms gem (Which only work in Rails 3). I am using cocooon gem instead. I am having this problem where "you have a date input in a nested field and you want to use jQuery datepicker for it. This is a bit tricky, because you have to activate datepicker after field was inserted."

The full description is under the Javascript events section here. https://github.com/ryanb/nested_form

I believe the solution is to use this code.

$(document).on('nested:fieldAdded', function(event){
  window.materializeForm.init()
})

It listens for the nested:fieldAdded event from the nested_form gem code. Does anyone know how I can find the event I need to listen for when using the cocoon gem? In order to reload the materializeForm when I created a new nested field so it picks up the date picker.

I can set up an example app in heroku if need be and the example is not clear but it's basically not rerunning materialise form when a new nested field is added by cocoon gem.

Any help will be much appreciated. Thanks.

Adding in my Html code >>>

// _form.html.erb file

   <h3>Dates</h3>
    <div id="schedules">
            <%= f.simple_fields_for :schedules do |schedule| %>
                <%= render 'schedule_fields', f: schedule %>
            <% end %>
            <div class="links">
                <%= link_to_add_association 'Add Schedule', f, :schedules %>
      </div>
    </div>

// _schedule_fields.html.erb file

<div class="nested-fields">
  <%= f.input :event_schedule, label_html: { class: "active"}, wrapper_html: { class: 'col m12 s12 ' }, class: "datepicker" %>
  <%= link_to_remove_association "Remove Schedule", f %>
</div>

* Solution code to make nested field work with callback *

$(document).on('cocoon:after-insert', (function(event) {
    window.materializeForm.init() 
}));

Solution

  • If you're referring to the event that's called on the insertion/removal of items then the below may help. Take a look at the official Github repo for Cocoon (Search for Callbacks) for more info. https://github.com/nathanvda/cocoon

    // A callback for cocoon so whenever a new association is made; the below will be executed.
    $(document).on('cocoon:after-insert', (function(event) {
    
    }