Formtastic Support

Peter Brown edited this page Jun 23, 2013 · 8 revisions
Clone this wiki locally

Formtastic Support

Built-in Formtastic support has been removed as of 2.0. You can use either of the following snippets to enable seamless support in your Formtastic forms. Both versions provide an :enum_select option:

<%= form.input :alarm_priority, :as => :enum_select %>

Note: ClassyEnum respects the :allow_blank and :allow_nil options and will include a blank select option in these cases.

Formtastic 2.x

Place the following in app/inputs/enum_select_input.rb

ClassyEnum 3.0

class EnumSelectInput < Formtastic::Inputs::SelectInput
  def collection
    enum = object.send(method)
    enum.class.select_options
  end

  def input_options
    enum = object.send(method)
    options[:selected] = enum.to_s
    options[:include_blank] = enum.allow_blank

    super()
  end
end

ClassyEnum 1.0 - 2.x

class EnumSelectInput < Formtastic::Inputs::SelectInput
  def collection
    enum_options = object.send("#{method}_options")
    enum_class = enum_options[:enum].to_s.classify.constantize
    enum_class.select_options
  end

  def input_options
    enum_options = object.send("#{method}_options")
    options[:selected] = object.send(method).to_s
    options[:include_blank] = enum_options[:allow_blank]

    super()
  end
end

Formtastic 1.x

Place the following at the bottom of config/initializers/formtastic.rb

ClassyEnum 3.0:

module ClassyEnum
  class SemanticFormBuilder < Formtastic::SemanticFormBuilder
    def enum_select_input(method, options)

      enum = object.send(method)

      options[:collection] = enum.class.select_options
      options[:selected] = enum.to_s
      options[:include_blank] = enum.allow_blank

      select_input(method, options)
    end
  end
end

Formtastic::SemanticFormHelper.builder = ClassyEnum::SemanticFormBuilder

ClassyEnum 1.0 - 2.x

module ClassyEnum
  class SemanticFormBuilder < Formtastic::SemanticFormBuilder
    def enum_select_input(method, options)

      enum_options = object.send("#{method}_options")
      enum_class = enum_options[:enum].to_s.classify.constantize

      options[:collection] = enum_class.select_options
      options[:selected] = object.send(method).to_s
      options[:include_blank] = enum_options[:allow_blank]

      select_input(method, options)
    end
  end
end

Formtastic::SemanticFormHelper.builder = ClassyEnum::SemanticFormBuilder