Wednesday, December 30, 2009

Recipe 2: In place editing with drop-down

(This post is one of a series that updates Chad Fowler's Rails Recipes for Rails 2.x.)

What. Like the first recipe, this one provides in-place editing. It is in-place editing of a country field. Instead of a text field, the editor control is a drop down list of countries.

How. The in-place editor plugin is extended to add this functionality.

Anachronisms.

  1. In place editing was moved out of Rails with version 2, so you will need the in placed editor plugin.

  2. The country list also moved out. Unfortunately, lists of countries are not without controversy, e.g., is Taiwan a country or a province? So there are multiple plugins that provide lists of countries.
  3. Some changes to the Scriptaculous interface require that another option be passed to Ajax.InPlaceSelectEditor.

Modifications.

1. The method in app/helpers/application_helper.rb should look like this:

  def in_place_select_editor(field_id, options = {})
js_options = {}
# Necessary for the submit to work
js_options['callback'] = "function(form) { return #{options[:with]} }" if options[:with]
# Necessary for the options to show up
js_options['selectOptionsHTML'] = %('#{escape_javascript(options[:select_options].gsub(/\n/, ""))}')

function = "new Ajax.InPlaceSelectEditor("
function << "'#{field_id}', "
function << "'#{url_for(options[:url])}'"
function << (', ' + options_for_javascript(js_options)) unless js_options.empty?
function << ')'

javascript_tag(function)
end

2. The following line must be added to the controller:
in_place_edit_for :contact, :country

No comments:

Post a Comment