Skip to content

Chaining Form Fields

activescaffold edited this page Sep 15, 2010 · 16 revisions

Sometimes you want update a form field after setting a value in another field. For example, you might have a form with a dropdown to select an author and another dropdown to select a book, and you want the book dropdown to only display books from the chosen author. To do this, 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[: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
In v2.3 you could use @options[:update_column] although it was deprecated and removed in v2.4
config.columns[:author].options[:update_column] = :book

The helper code is to show only books belonging to chosen author, as 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