diff --git a/README b/README index e69de29..445fd4b 100644 --- a/README +++ b/README @@ -0,0 +1 @@ +better forms in rails. foshizzle! \ No newline at end of file diff --git a/init.rb b/init.rb new file mode 100644 index 0000000..469e504 --- /dev/null +++ b/init.rb @@ -0,0 +1 @@ +require "lib/better_form_helper" \ No newline at end of file diff --git a/lib/better_form_helper.rb b/lib/better_form_helper.rb new file mode 100644 index 0000000..924dd93 --- /dev/null +++ b/lib/better_form_helper.rb @@ -0,0 +1,61 @@ +module BetterFormHelper + def better_form_field(form, obj, field, field_type, label, required=false, help_text='', options = {}) + content_tag('fieldset', :class => field_type) do + content_tag('span', help_text, :class => 'help-text') + + form.label(field, label + required(required)) + + form.send(field_type, field, options) + + better_error_message_for(obj, field) + end + end + + def better_form_for(obj, opts={}, &block) + opts[:html] ||= {} + opts[:html].merge!({:class => 'better'}) + + concat("
") + form_for(obj, opts, &block) + concat("
") + end + + def cancel_and_submit(form, cancel_path, submit_text="Save") + link_to('Cancel', cancel_path, :class => 'cancel') + + form.submit(submit_text, :id => 'commit') + end + + def required(x) + "*" + end + + def better_text_field(form, obj, field, label, required=false, help_text='') + better_form_field(form, obj, field, :text_field, colonize(label), required, help_text) + end + + def better_text_area(form, obj, field, label, required=false) + better_form_field(form, obj, field, :text_area, colonize(label), required) + end + + def better_password_field(form, obj, field, label, required=true, options = {}) + better_form_field(form, obj, field, :password_field, colonize(label), required, '', options) + end + + def colonize(label) + label =~ /[:\?]$/ ? label : "#{label}:" + end + + def better_error_message_for(object, method, *args) + options = args.extract_options! + options.reverse_merge!(:prepend_text => '', :append_text => '', :css_class => 'formError') + + if (obj = (object.respond_to?(:errors) ? object : instance_variable_get("@#{object}"))) && + (errors = obj.errors.on(method)) + error_to_display = errors.is_a?(Array) ? errors.first : errors + error_to_display.gsub!(/^\^/, '') + content_tag("span", + "#{options[:prepend_text]}#{ERB::Util.html_escape(error_to_display)}#{options[:append_text]}", + :class => options[:css_class] + ) + else + '' + end + end +end