简体   繁体   中英

Activeadmin form select dropdown update

I have a Category Model and a SubCategory Model and id like the SubCategory select input to refresh depending on the SubCategories that are associated to the specific Category I have selected.

form do |f|
    f.inputs do
        f.input :title
        f.input :category, as: :select, collection: Category.all, :input_html => { :class => 'chzn-select', :width => 'auto', "data-placeholder" => 'Click' }
        f.input :sub_category, as: :select, collection: SubCategory.all, :input_html => { :class => 'chzn-select', :width => 'auto', "data-placeholder" => 'Click' }
    end
    f.actions
end

You can use dependent select for this purpose. Example is given here

Active Admin

ActiveAdmin.register CatalogsProduct do
  form do |f|
    f.inputs "Details" do
      f.input :product, :as => :select, :collection => Product.all.collect {|product| [product.name, product.id] }
      f.input :catalog, :as => :select, :input_html => {'data-option-dependent' => true, 'data-option-url' => '/products/:catalogs_product_product_id/catalogs', 'data-option-observed' => 'catalogs_product_product_id'}, :collection => (resource.product ? resource.product.category.catalogs.collect {|catalog| [catalog.attr_name, catalog.id]} : []) 
    end
    f.actions
  end
end

Catalog controller

class CatalogsController < ApplicationController
  respond_to :json

  def index
    if params[:product_id]
      product = Product.find_by_id(params[:product_id])
      @catalogs = product.category.catalogs
    else
      @catalogs = Catalog.all
    end
    render :json => @catalogs.collect {|catalog| {:id => catalog.id, :name => catalog.attr_name} }
  end
end
  1. You have to create a member action (method: GET, params: the id of the selected Category) in the ActiveAdmin Category model that returns the SubCategories (in json, for example) belongs to the selected Category:

    https://github.com/activeadmin/activeadmin/blob/master/docs/8-custom-actions.md#member-actions

  2. You have to use jQuery (for exmaple) with ajax, that populate the SubCategory select input when the Category select input has been changed:

    Populate Select box options on click with Javascript/Jquery with Json data https://forum.jquery.com/topic/best-practices-for-populating-selects-with-ajax

you can do something like this to add specific selection

form do |f|
            f.inputs do
            f.input :category , :as => :select, collection: (['conversion','double-bar', 'fixed-hybrid','removal-bar-over-denture', 'surgical-guides'])
  
            end
            actions 
          end

You can apply this, I did it by relating games to categories and subcategories. Working on Ruby on Rails 6.0.4 and Active Admin 2.9.0.

Models

class Game < ApplicationRecord 
  belongs_to :category
  belongs_to :sub_category
end

class Category < ApplicationRecord 
  has_many :sub_categories
end

class SubCategory < ApplicationRecord 
  belongs_to :category
end

Active admin form

ActiveAdmin.register Game do
  form do |f|
    f.inputs "Details" do
      f.input :category_id, as: :select, collection: Category.all
      f.input :sub_category_id, as: :select, collection: ([]) # The input is initialized without values
    end
    f.actions
  end
end

You must do the following:

  1. Create a controller, that returns the subcategories.

     class SubCategoriesController < ApplicationController def sub_category_filter if params[:category_id] category = Category.find(params[:category_id]) @sub_categories = category.sub_categories else @sub_categories = [] end render:json => @sub_categories.collect {|sub_category| {:id => sub_category.id, :name => sub_category.name} } end end
  2. Add the route in the routes.rb file.

     get 'sub_category_filter/' => 'sub_category#sub_category_filter'
  3. Inspect with your web browser console your selects, and use a CSS selector to create a jQuery object for the category select, something like:

     $('#game_category_id')
  4. Add this block of code in the file /app/assets/javascripts/active_admin.js , which is responsible for making the call to the generated controller, and adding the options that it returns.

     //= require active_admin/base $(function () { $('#game_category_id').on('change', function () { $('#game_sub_category_id option').remove(); // Remove all <option> child tags. $.getJSON(`/sub_category_filter`, {category_id: $(this).val()}, function(result){ // Documentation on getJSON: http://api.jquery.com/jQuery.getJSON/ $.each(result, function (i, item) { // Iterates through a collection $('#game_sub_category_id').append($('<option>', { // Append an object to the inside of the select box value: item.id, text: item.name })); }); }); }) })

References:

Can't find the error in my dependent select drop down on Active Admin( Rails 3.2, Active Admin 1.0)

Populate Select box options on click with Javascript/Jquery with Json data

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