Search code examples
ruby-on-railsactiveadminformtastic

ActiveAdmin guidance for working on custom form (custom action?)


I'm looking for some guidance to make a custom form with ActiveAdmin. This is not a regular form, but I actually need some JavaScript on it. However, I'm not familiar with ActiveAdmin right now.

I have a form that will collect a Product list. Every time I add a Product to the list, I need to recalculate the sub-total for the order (based on quantity and unique price).

For adding the products I'm using regular Formtastic, like this:

f.inputs "Product List" do
  f.has_many :product_lists do |detail|
    detail.input  :good_id, :as => :select,
                  :collection => Good.accessible_by(current_ability, :read),
                  :input_html => { class: 'chosen-select' },
                  :include_blank => true
    detail.input :quantity, :input_html => { :value => 1 }
  end
end

However, I came across to multiple questions:

  • How should I recalculate the sub-totals every time I add a new product on the list? Should I use a custom collection action? I was even considering a Backbone App inside of it, for handling the whole process.
  • Is there a better way, instead of using a Custom Action?
  • Is there a good way to use a custom action ONLY for the new form? I was able to make a new one, but I was not able to have control over the form.
  • How can I have better control of the form panel? I was not able to add panels inside the form block :(.

Solution

  • If you are using >= 1.0.0.pre from the master branch:

    • you should be able to wrap a has_many block inside of an f.inputs block if you want them to be in a panel.
    • there are callbacks for before/after add/remove for has-many forms. You might be able to hook into those for recalculating (at least on removals). For additions, you might want to consider adding a change listener for whatever should trigger recalculation. You can add that listener on page load and/or after a new item is added.

    Is your total being recalculated on the server side or on the client side when you add items? If on the server side, the total should be updated after the form is submitted, and that logic probably belongs in your model. AA has-many adds fields to the form, which in turn gets submitted and then committed. Adding a new nested fieldset does not change anything on the server until the whole form is submitted. If it should be updated without committing, you'll need to handle the ajax request and responses yourself, but you should be able to simply use the default actions and either request the json format back or create a custom javascript template.