Multiple select in administrate

1.7k Views Asked by At

Since administrate does not yet have support for multiple selects. Has anyone created a custom multiple select? Preferably one that works like the HasMany select.

1

There are 1 best solutions below

4
On BEST ANSWER

Here it is in case someone else needs it:

app/fields/multiple_select_field.rb

# app/fields/multiple_select_field.rb

require "administrate/field/base"

class MultipleSelectField < Administrate::Field::Select

  def to_s
    data
  end

  def self.permitted_attribute(attribute)
    { attribute.to_sym => [] }
  end

  def permitted_attribute
    self.class.permitted_attribute(attribute)
  end

end

app/views/fields/multiple_select_field/_form.html.erb

# app/views/fields/multiple_select_field/_form.html.erb

<div class="field-unit__label">
  <%= f.label field.attribute %>
</div>
<div class="field-unit__field">
  <%= f.select(
    field.attribute,
    options_from_collection_for_select(
      field.selectable_options,
      :to_s,
      :to_s,
      field.data.presence,
    ),
    {}, multiple: true,
  ) %>
</div>

app/views/fields/multiple_select_field/_index.html.erb

# app/views/fields/multiple_select_field/_index.html.erb
<%= field.to_param.join(', ') %>

app/views/fields/multiple_select_field/_show.html.erb

# app/views/fields/multiple_select_field/_show.html.erb
<%= field.to_param.join(', ') %>