:ruby
  related_id = params[:associations] && params[:associations][field.name.to_s]
  config = field.associated_model_config
  source_abstract_model = RailsAdmin.config(form.object.class).abstract_model

  if form.object.new_record? && related_id.present? && related_id != 'new'
    selected = [config.abstract_model.get(related_id)]
  else
    selected = form.object.send(field.name)
  end
  selected_ids = selected.map{|s| s.send(field.associated_primary_key)}

  current_action = params[:action].in?(['create', 'new']) ? 'create' : 'update'

  xhr = !field.associated_collection_cache_all

  collection = if xhr
    selected.map { |o| [o.send(field.associated_object_label_method), o.send(field.associated_primary_key)] }
  else
    i = 0
    controller.list_entries(config, :index, field.associated_collection_scope, false).map { |o| [o.send(field.associated_object_label_method), o.send(field.associated_primary_key)] }.sort_by {|a| [selected_ids.index(a[1]) || selected_ids.size, i+=1] }
  end

  js_data = {
    xhr: xhr,
    :'edit-url' => (authorized?(:edit, config.abstract_model) ? edit_path(model_name: config.abstract_model.to_param, id: '__ID__') : ''),
    remote_source: index_path(config.abstract_model, source_object_id: form.object.id, source_abstract_model: source_abstract_model.to_param, associated_collection: field.name, current_action: current_action, compact: true),
    sortable: !!field.orderable,
    removable: !!field.removable,
    cacheAll: !!field.associated_collection_cache_all,
    regional: {
      chooseAll: t("admin.misc.chose_all"),
      chosen: t("admin.misc.chosen", name: config.label_plural),
      clearAll: t("admin.misc.clear_all"),
      search: t("admin.misc.search"),
      up: t("admin.misc.up"),
      down: t("admin.misc.down")
    }
  }

%input{name: form.dom_name(field), type: "hidden", value: ""}

- selected_ids = (hdv = field.form_default_value).nil? ? selected_ids : hdv
= form.select field.method_name, collection, { selected: selected_ids, object: form.object }, field.html_attributes.reverse_merge({data: { filteringmultiselect: true, options: js_data.to_json }, multiple: true})
- if authorized?(:new, config.abstract_model) && field.inline_add
  - path_hash = { model_name: config.abstract_model.to_param, modal: true }
  - path_hash.merge!({ associations: { field.inverse_of => (form.object.persisted? ? form.object.id : 'new') } }) if field.inverse_of
  = link_to "<i class=\"icon-plus icon-white\"></i> ".html_safe + wording_for(:link, :new, config.abstract_model), '#', data: { link: new_path(path_hash) }, class: "create btn btn-info", style: 'margin-left:10px'
