Skip to content

Instantly share code, notes, and snippets.

@sandipransing
Created September 1, 2010 08:14
Show Gist options
  • Select an option

  • Save sandipransing/560394 to your computer and use it in GitHub Desktop.

Select an option

Save sandipransing/560394 to your computer and use it in GitHub Desktop.
form builder
class MyformBuilder < ActionView::Helpers::FormBuilder
def self.create_tagged_field(method_name)
define_method(method_name) do |name, *args|
if object && object.errors.any?
errors = object.errors.on(name.to_sym)
errors = errors.join(', ') if errors.kind_of? Array
end
help = Help[object.class.to_s][name.to_s] if Help[object.class.to_s]
# initialize some local variables
label = klass = ''
if args.last.is_a?(Hash)
arg_label = args.last[:label].to_s
arg_hint = args.last[:hint].to_s
arg_suffix = args.last[:suffix].to_s
arg_klass = args.last[:class].to_s
arg_required = args.last[:required].to_s
end
if help
arg_label = help['label'] if help['label']
arg_hint = help['hint'] if help['hint']
end
#Label text, titlize field name if a custom label isn't passed
label = arg_label.blank? ? name.to_s.titleize : arg_label
#Label none then make it nil
label = nil if label == 'none'
klass = if %w[text_field password_field date_select datetime_select input_field calendar_date_select].include? method_name
'input_field'
end
options = args.last.present? ? args.last : {}
options[:class] = klass if klass.present?
content = ""
hint = @template.content_tag(:span, arg_hint, :class => :hint) if arg_hint
content << @template.content_tag(:label, "#{label}", :for => "#{@object_name}_#{name}") if label
ex_content = method_name == 'select' ? super : super(name, options)
# Required Field Notations
# all: add required notation for all form methods
# new: only for 'create new' forms, using the form in 'edit' mode should disregard
ex_content << @template.content_tag("strong", "*", :class => :required) if arg_required == 'all' || (arg_required == 'new' && object.new_record?)
ex_content<<@template.content_tag(:div, errors, :class => :error) if errors.present?
@template.content_tag :li, content<<ex_content
end
end
helpers = %w[check_box text_field text_area password_field select date_select datetime_select file_field collection_select state_select label calendar_date_select]
helpers.each do |name|
create_tagged_field(name)
end
end
</code>
Usage
<% form_for @user, :url => users_path , :builder => MyformBuilder, :html => {:id => :settings} do |f| %>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment