简体   繁体   中英

Rails nested form with select2

I use cocoon gem for the nested forms and use select2 for the custom selects.

The first collection select has worked as expected. When I add another select item even though the select items have the same class, it hasn't worked. I tried this solution. But it hasn't solved to my problem. Because I have called as a partial to nested items.

_form.html

 <%= simple_form_for(@course) do |f| %>
   <%= f.simple_fields_for :course_teachers do |course_teacher| %>
     <%= render "course_teacher_fields", :f => course_teacher %>
   <% end %>
   <div class="links">
     <%= link_to_add_association 'Add Teacher', f, :course_teachers, class:"btn btn-info" %>
   </div>
 <%end%>

_course_teacher_fields.html

<div class="nested-fields">
  <%= f.association :teacher, collection: Teacher.all, label_method: :full_name_with_title, input_html: {class: "teacher"} %><br/>
</div>

app.js

$(".teacher").select2({
  placeholder: "Select Teacher",
  allowClear: true
});

Do you have any idea?

Problem is that your javascript is initializing select2 only once, on the items that have been rendered (that is why you don't have problems with the first select) but after you add another one, select2() doesn't fire and is not initialized on that item.

To fix this, add a callback after `cocoon:after-insert' and fire the select2 event on the added row.

So your javascript would be something like

function init_select2(selector){
  $(selector).select2({
    placeholder: "Select Teacher",
    allowClear: true
  });
};

init_select2(".teacher")

$("form").on("cocoon:after-insert", function(_, row){
  field = $(row).find(".teacher")
  init_select2(field);
});

I have not tested this code, but I hope you get the Idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM