Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

in progress

  • Loading branch information...
commit 19f075dbd4beb9b146330adf3c1fe8badc822989 1 parent 50149b0
Mike Blyth authored

Showing 1 changed file with 63 additions and 0 deletions. Show diff stats Hide diff stats

  1. +63 0 app/form builders/bootstrap_form_builder.rb
63 app/form builders/bootstrap_form_builder.rb
... ... @@ -0,0 +1,63 @@
  1 +# Based on Railscasts episode 311, by Ryan Bates
  2 +# LIMITATION: tag ID is formed from name, so will not be unique if the same name is used
  3 +# more than once on a page!
  4 +
  5 +class LabeledFormBuilder < ActionView::Helpers::FormBuilder
  6 + delegate :content_tag, :tag, to: :@template
  7 +
  8 + %w[text_field text_area password_field collection_select].each do |method_name|
  9 + define_method(method_name) do |name, *args|
  10 + content_tag :div, class: "field" do
  11 + field_label(name, *args) + tag(:br) + super(name, *args)
  12 + end
  13 + end
  14 + end
  15 +
  16 + def check_box(name, *args)
  17 + content_tag :div, class: "field" do
  18 + super + " " + field_label(name, *args)
  19 + end
  20 + end
  21 +
  22 + def collection_check_boxes(attribute, records, record_id, record_name)
  23 + content_tag :div, class: "field" do
  24 + @template.hidden_field_tag("#{object_name}[#{attribute}][]") +
  25 + records.map do |record|
  26 + element_id = "#{object_name}_#{attribute}_#{record.send(record_id)}"
  27 + checkbox = @template.check_box_tag("#{object_name}[#{attribute}][]", record.send(record_id), object.send(attribute).include?(record.send(record_id)), id: element_id)
  28 + checkbox + " " + @template.label_tag(element_id, record.send(record_name))
  29 + end.join(tag(:br)).html_safe
  30 + end
  31 + end
  32 +
  33 + def submit(*args)
  34 + content_tag :div, class: "actions" do
  35 + super
  36 + end
  37 + end
  38 +
  39 + def error_messages
  40 + if object.errors.full_messages.any?
  41 + content_tag(:div, :class => "error_messages") do
  42 + content_tag(:h2, "Invalid Fields") +
  43 + content_tag(:ul) do
  44 + object.errors.full_messages.map do |msg|
  45 + content_tag(:li, msg)
  46 + end.join.html_safe
  47 + end
  48 + end
  49 + end
  50 + end
  51 +
  52 + private
  53 +
  54 + def field_label(name, *args)
  55 + options = args.extract_options!
  56 + required = object.class.validators_on(name).any? { |v| v.kind_of? ActiveModel::Validations::PresenceValidator }
  57 + label(name, options[:label], class: ("required" if required), for: "#{name}_id")
  58 + end
  59 +
  60 + def objectify_options(options)
  61 + super.except(:label)
  62 + end
  63 +end

0 comments on commit 19f075d

Please sign in to comment.
Something went wrong with that request. Please try again.