Mathieu
Mathieu

Reputation: 4797

Dynamically-adjusting drop down fields on Active Admin form (rails 3.2)

I have a very basic architecture on my Ruby on Rails app:

On my active admin form page, I want to put fields so that for each company, I first select in a drop down the industry it belongs to (this works so far), and then another field "sub industry", that would ONLY display, according to the industry I selected in the previous field, the subindustries that I have categorized previously in this industry.

For example, coca would go in industry "Drinks and beverage" and I'd like the form to dynamically adjust and only show in the field "sub indsutry" :a dropdown with "hot drinks", "cold drinks", "tea", "sodas"

form do |f|

    f.inputs "Company" do

      f.input :company_industry_id,    :label => "Select industry:",             :as => :select, :collection => CompanyIndustry.all
      f.input :company_subindfustry_id, :label => "Select subindustry:",  :as => :select, :collection => CompanySubindustry.all
end

Obviously I have a problem as so far, it show me ALL the subindustries I have and not only the subindustries WITHIN the industry I select on the previous field.

Does anyone know how I can solve that ?

Upvotes: 0

Views: 4019

Answers (2)

Whoa
Whoa

Reputation: 1334

I chose to approach this in a quick and dirty, non AJAX fashion. It worked well for my scenario.

Note that the non-applicable items in the secondary select are disabled, not hidden. If you really need to hide them, I would clone & rebuild the select instead of disabling specific options.

#...
f.input :user, :input_html => {
  ##Manipulate Location select based on selected User
  :onchange => "
    var user = $(this).val();

    $('#order_location_id').val(0).find('option').each(function(){
      var $option = $(this),
        isCorrectUser = ($option.attr('data-user') === user);  

        $option.prop('disabled',!isCorrectUser);
    });
  "
}
##Insert necessary Location info into DOM
f.input :location, collection: Location.all.map{ |loc|
  [loc.name,loc.id, {"data-user" => loc.user_id}]
}
#...

Upvotes: 5

CDub
CDub

Reputation: 13364

You'll need to do either a page refresh to update data based on what's selected or (my preference) an AJAX call to update the other dropdown after the first one is selected.

There's a great railscast on doing just this - that would be a great place to start.

Upvotes: 2

Related Questions