Skip to content

Chaining Form Fields

aehrlich edited this page Sep 14, 2010 · 16 revisions

Sometimes you want update a form field after set a value in other field, for example, you have a form with a dropdown to select an author and another dropdown to select a book, and you want select books from the chosen author. So you need to render the books dropdown each time an author is chosen.

class UsersController < ApplicationController
  active_scaffold do |config|
    config.columns[:author].form_ui = :select
    config.columns[:author].update_column = :book # enables the "magic"
#    config.columns[:author].options[:update_column] = :book # works only this way with latest AS (ROR 2.3.8)?! aehrlich 17.06.2010
    config.columns[:book].form_ui = :select
  end
end

module UsersHelper
  def options_for_association_conditions(association)
    if association.name == :book
      {'books.author_id' => @record.author_id}
    else
      super
    end
  end
end

The helper code is to show only books belonging to chosen author, like is explained in Custom Association Options.
Chaining form fields works with simple columns and form overrides too, not only with association columns.

You can set an array of columns to update multiple columns when a column changes, and chain column updates:

class UsersController < ApplicationController
  active_scaffold do |config|
    config.columns[:author].form_ui = :select
    config.columns[:author].update_column = [:book, :editorial]
    config.columns[:book].form_ui = :select
    config.columns[:book].update_column = :format
  end
end

In this example, fields for book, editorial and format are updated when author changes, and when book changes only format is updated.

Usually only the value of the changed column is sent, if you need another values to render the updated columns, enable send_form_on_update_column and all the form will be sent.

Clone this wiki locally