Class: Console::Formtastic::BootstrapFormBuilder

Inherits:
Formtastic::SemanticFormBuilder
  • Object
show all
Defined in:
lib/console/formtastic/bootstrap_form_builder.rb

Instance Method Summary collapse

Constructor Details

#initialize(object_name, object, template, options, proc) ⇒ BootstrapFormBuilder

Returns a new instance of BootstrapFormBuilder.



7
8
9
10
11
12
13
14
15
# File 'lib/console/formtastic/bootstrap_form_builder.rb', line 7

def initialize(object_name, object, template, options, proc)
  options[:html] ||= {}
  class_names = options[:html][:class] ? options[:html][:class].split(" ") : []

  class_names << 'form-inline' if options[:simple]
  options[:html][:class] = class_names.join(" ")

  super
end

Instance Method Details

#basic_input_helper(form_helper_method, type, method, options) ⇒ Object

wrap contents in div.controls



227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
# File 'lib/console/formtastic/bootstrap_form_builder.rb', line 227

def basic_input_helper(form_helper_method, type, method, options) #:nodoc:
  html_options = options.delete(:input_html) || {}
  html_options = default_string_options(method, type).merge(html_options) if [:numeric, :string, :password, :text, :phone, :search, :url, :email].include?(type)
  field_id = generate_html_id(method, "")
  html_options[:id] ||= field_id
  label_options = options_for_label(options)
  label_options[:class] ||= 'control-label'
  label_options[:for] ||= html_options[:id]

  control_content = parts(method, options) do
    send(respond_to?(form_helper_method) ? form_helper_method : :text_field, method, html_options)
  end

  safe_control_content = ::Formtastic::Util.html_safe(control_content)
  input_inline? ? safe_control_content : label(method, label_options) << template.(:div, safe_control_content, {:class => 'controls'}) #added class
  # end changes
end

#boolean_input(method, options) ⇒ Object



295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
# File 'lib/console/formtastic/bootstrap_form_builder.rb', line 295

def boolean_input(method, options)
  html_options  = options.delete(:input_html) || {}
  checked_value = options.delete(:checked_value) || '1'
  unchecked_value = options.delete(:unchecked_value) || '0'
  checked = @object && ActionView::Helpers::InstanceTag.check_box_checked?(@object.send(:"#{method}"), checked_value)

  html_options[:id] = html_options[:id] || generate_html_id(method, "")
  input_html = template.check_box_tag(
    "#{@object_name}[#{method}]",
    checked_value,
    checked,
    html_options
  )

  label_options = options_for_label(options)
  label_options[:for] ||= html_options[:id]
  (label_options[:class] ||= []) << 'checkbox'

  input_html << localized_string(method, label_options[:label], :label) || humanized_attribute_name(method)
  label_options.delete :label

  safe_input_html = ::Formtastic::Util.html_safe(input_html)

  return safe_input_html if input_inline?

  template.(:div, label(method, safe_input_html, label_options), {:class => 'controls'}) << template.hidden_field_tag((html_options[:name] || "#{@object_name}[#{method}]"), unchecked_value, :id => nil, :disabled => html_options[:disabled])
end

#buttons(*args) ⇒ Object

set the default css class



18
19
20
21
22
# File 'lib/console/formtastic/bootstrap_form_builder.rb', line 18

def buttons(*args)
  options = args.extract_options!
  options[:class] ||= @options[:simple] ? 'btn-toolbar' : 'form-actions'
  super *(args << options)
end

#commit_button(*args) ⇒ Object

remove the button wrapper



324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
# File 'lib/console/formtastic/bootstrap_form_builder.rb', line 324

def commit_button(*args)
  options = args.extract_options!
  text = options.delete(:label) || args.shift

  if @object && (@object.respond_to?(:persisted?) || @object.respond_to?(:new_record?))
    if @object.respond_to?(:persisted?) # ActiveModel
      key = @object.persisted? ? :update : :create
    else # Rails 2
      key = @object.new_record? ? :create : :update
    end

    # Deal with some complications with ActiveRecord::Base.human_name and two name models (eg UserPost)
    # ActiveRecord::Base.human_name falls back to ActiveRecord::Base.name.humanize ("Userpost")
    # if there's no i18n, which is pretty crappy.  In this circumstance we want to detect this
    # fall back (human_name == name.humanize) and do our own thing name.underscore.humanize ("User Post")
    if @object.class.model_name.respond_to?(:human)
      object_name = @object.class.model_name.human
    else
      object_human_name = @object.class.human_name                # default is UserPost => "Userpost", but i18n may do better ("User post")
      crappy_human_name = @object.class.name.humanize             # UserPost => "Userpost"
      decent_human_name = @object.class.name.underscore.humanize  # UserPost => "User post"
      object_name = (object_human_name == crappy_human_name) ? decent_human_name : object_human_name
    end
  else
    key = :submit
    object_name = @object_name.to_s.send(label_str_method)
  end

  text = (localized_string(key, text, :action, :model => object_name) ||
          ::Formtastic::I18n.t(key, :model => object_name)) unless text.is_a?(::String)

  button_html = options.delete(:button_html) || {}
  button_html.merge!(:class => [button_html[:class] || 'btn btn-primary', key].compact.join(' '))

  #remove need for wrapper
  #wrapper_html_class = ['btn-primary'] #changed # TODO: Add class reflecting on form action.
  #wrapper_html = options.delete(:wrapper_html) || {}
  #wrapper_html[:class] = (wrapper_html_class << wrapper_html[:class]).flatten.compact.join(' ')

  accesskey = (options.delete(:accesskey) || default_commit_button_accesskey) unless button_html.has_key?(:accesskey)
  button_html = button_html.merge(:accesskey => accesskey) if accesskey
  submit(text, button_html) # no wrapper
end

#error_list(errors, options = {}) ⇒ Object

:nodoc:



109
110
111
112
# File 'lib/console/formtastic/bootstrap_form_builder.rb', line 109

def error_list(errors, options = {}) #:nodoc:
  error_class = options[:error_class] || default_inline_error_class
  template.(:p, errors.join(' ').untaint, :class => error_class)
end

#field_set_and_list_wrapping(*args, &block) ⇒ Object

override tag creation



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/console/formtastic/bootstrap_form_builder.rb', line 30

def field_set_and_list_wrapping(*args, &block) #:nodoc:
  contents = args.last.is_a?(::Hash) ? '' : args.pop.flatten
  html_options = args.extract_options!

  legend  = html_options.dup.delete(:name).to_s
  legend %= parent_child_index(html_options[:parent]) if html_options[:parent]
  legend  = template.(:legend, template.(:span, ::Formtastic::Util.html_safe(legend))) unless legend.blank?

  if block_given?
    contents = if template.respond_to?(:is_haml?) && template.is_haml?
      template.capture_haml(&block)
    else
      template.capture(&block)
    end
  end

  # Ruby 1.9: String#to_s behavior changed, need to make an explicit join.
  contents = contents.join if contents.respond_to?(:join)
  fieldset = template.(:fieldset,
    ::Formtastic::Util.html_safe(legend) << ::Formtastic::Util.html_safe(contents), #changed
    html_options.except(:builder, :parent)
  )
  template.concat(fieldset) if block_given? && !::Formtastic::Util.rails3?
  fieldset
end

#inline_errors_for(method, options = {}) ⇒ Object

:nodoc:



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/console/formtastic/bootstrap_form_builder.rb', line 93

def inline_errors_for(method, options = {}) #:nodoc:
  return nil unless render_inline_errors?
  errors = error_keys(method, options).map do |x|
    attribute = localized_string(x, x.to_sym, :label) || humanized_attribute_name(x)
    @object.errors[x].map do |error| 
      (error[0,1] == error[0,1].upcase) ? error : [attribute, error].join(" ")
    end
  end.flatten.compact.uniq
  return nil unless errors.any?
  if input_inline?
    @input_inline_errors << errors
    return nil
  end
  send(:"error_#{inline_errors}", [*errors], options) 
end

#inline_fields_and_wrapping(*args, &block) ⇒ Object



147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/console/formtastic/bootstrap_form_builder.rb', line 147

def inline_fields_and_wrapping(*args, &block)
  contents = args.last.is_a?(::Hash) ? '' : args.pop.flatten
  html_options = args.extract_options!

  html_options.delete(:inline)
  html_class = ['control-group']
  html_class << 'control-group-important' if html_options.delete(:important)

  label = template.(:label, ::Formtastic::Util.html_safe(html_options.dup.delete(:name).to_s) << required_or_optional_string(html_options.delete(:required)), { :class => 'control-label' }) if html_options[:name]

  # Generate form elements
  if block_given?
    contents = if template.respond_to?(:is_haml?) && template.is_haml?
      template.capture_haml(&block)
    else
      template.capture(&block)
    end
  end

  # Ruby 1.9: String#to_s behavior changed, need to make an explicit join.
  #contents = contents.join if contents.respond_to?(:join)
  unless html_options[:without_errors]
    contents << send(:"error_#{inline_errors}", [*@input_inline_errors], {})
    html_class << 'error' unless @input_inline_errors.empty?
  end

  @input_inline_hints.each do |hint|
    contents << template.(:p, hint, :class => default_hint_class)
  end

  template.(:div, ::Formtastic::Util.html_safe(label || '') << template.(:div, ::Formtastic::Util.html_safe(contents), {:class => 'controls'}), { :class => html_class.join(' ') })
end

#inline_hints_for(method, options) ⇒ Object

:nodoc:



82
83
84
85
86
87
88
89
90
91
# File 'lib/console/formtastic/bootstrap_form_builder.rb', line 82

def inline_hints_for(method, options) #:nodoc:
  options[:hint] = localized_string(method, options[:hint], :hint)
  return if options[:hint].blank? or options[:hint].kind_of? Hash
  if input_inline?
    @input_inline_hints << options[:hint]
    return nil
  end
  hint_class = options[:hint_class] || default_hint_class
  template.(:p, ::Formtastic::Util.html_safe(options[:hint]), :class => hint_class)
end

#input(method, options = {}) ⇒ Object

change from li to div.control-group, move hints/errors into the input block



185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/console/formtastic/bootstrap_form_builder.rb', line 185

def input(method, options = {})
  options = options.dup # Allow options to be shared without being tainted by Formtastic

  options[:required] = method_required?(method) unless options.key?(:required)
  options[:as]     ||= default_input_type(method, options)

  html_class = [ 
    options[:as], 
    options[:required] ? :required : :optional, 
    'control-group',
  ] #changed
  html_class << 'control-group-important' if options[:important]

  wrapper_html = options.delete(:wrapper_html) || {}
  if has_errors?(method, options)
    html_class << 'error'

    wrapper_html[:"data-server-error"] = "server-error"
  end
  wrapper_html[:id]  ||= generate_html_id(method)
  wrapper_html[:class] = (html_class << wrapper_html[:class]).flatten.compact.join(' ')

  if options[:input_html] && options[:input_html][:id]
    options[:label_html] ||= {}
    options[:label_html][:for] ||= options[:input_html][:id]
  end

  # moved hint/error output inside basic_input_helper
  safe_html_output = ::Formtastic::Util.html_safe(inline_input_for(method, options))
  return safe_html_output if input_inline?
  template.(:div, safe_html_output, wrapper_html) #changed to move to basic_input_helper
end

#input_inline?Boolean

Returns:

  • (Boolean)


180
181
182
# File 'lib/console/formtastic/bootstrap_form_builder.rb', line 180

def input_inline?
  @input_inline
end

#inputs(*args, &block) ⇒ Object



114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/console/formtastic/bootstrap_form_builder.rb', line 114

def inputs(*args, &block)
  title = field_set_title_from_args(*args)
  html_options = args.extract_options!
  html_options[:class] ||= "inputs"
  html_options[:name] = title

  if html_options[:for] # Nested form
    inputs_for_nested_attributes(*(args << html_options), &block)
  elsif html_options[:inline]
    @input_inline = true
    @input_inline_errors = []
    @input_inline_hints = []
    fieldset = inline_fields_and_wrapping(*(args << html_options), &block)
    @input_inline = false
    @label = nil
    fieldset
  elsif block_given?
    field_set_and_list_wrapping(*(args << html_options), &block)
  else
    if @object && args.empty?
      args  = association_columns(:belongs_to)
      args += content_columns
      args -= RESERVED_COLUMNS
      args.compact!
    end
    legend = args.shift if args.first.is_a?(::String)
    contents = args.collect { |method| input(method.to_sym) }
    args.unshift(legend) if legend.present?

    field_set_and_list_wrapping(*((args << html_options) << contents))
  end
end

#loading(*args) ⇒ Object



24
25
26
27
# File 'lib/console/formtastic/bootstrap_form_builder.rb', line 24

def loading(*args)
  image = template.instance_variable_get(:@loader_image) || template.image_path('loader.gif')
  template.(:img, nil, :alt => 'Working...', 'data-loading' => 'true', :class => 'icon-loading', :style => 'display: none', :src => image)
end

#parts(method, options, &block) ⇒ Object



218
219
220
221
222
223
224
# File 'lib/console/formtastic/bootstrap_form_builder.rb', line 218

def parts(method, options, &block)
  input_parts = (custom_inline_order[options[:as]] || inline_order).dup
  input_parts = input_parts - [:errors, :hints] if options[:as] == :hidden
  input_parts.map do |type|
    (:input == type) ? yield : send(:"inline_#{type}_for", method, options)
  end.compact.join("\n")
end

#select_input(method, options) ⇒ Object

wrap select in a control



246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
# File 'lib/console/formtastic/bootstrap_form_builder.rb', line 246

def select_input(method, options)
  html_options = options.delete(:input_html) || {}
  html_options[:multiple] = html_options[:multiple] || options.delete(:multiple)
  html_options.delete(:multiple) if html_options[:multiple].nil?

  reflection = reflection_for(method)
  if reflection && [ :has_many, :has_and_belongs_to_many ].include?(reflection.macro)
    html_options[:multiple] = true if html_options[:multiple].nil?
    html_options[:size]     ||= 5
    options[:include_blank] ||= false
  end
  options = set_include_blank(options)
  input_name = generate_association_input_name(method)
  html_options[:id] ||= generate_html_id(input_name, "")

  select_html = if options[:group_by]
    # The grouped_options_select is a bit counter intuitive and not optimised (mostly due to ActiveRecord).
    # The formtastic user however shouldn't notice this too much.
    raw_collection = find_raw_collection_for_column(method, options.reverse_merge(:find_options => { :include => options[:group_by] }))
    label, value = detect_label_and_value_method!(raw_collection, options)
    group_collection = raw_collection.map { |option| option.send(options[:group_by]) }.uniq
    group_label_method = options[:group_label_method] || detect_label_method(group_collection)
    group_collection = group_collection.sort_by { |group_item| group_item.send(group_label_method) }
    group_association = options[:group_association] || detect_group_association(method, options[:group_by])

    # Here comes the monster with 8 arguments
    grouped_collection_select(input_name, group_collection,
                                   group_association, group_label_method,
                                   value, label,
                                   strip_formtastic_options(options), html_options)
  else
    collection = find_collection_for_column(method, options)

    select(input_name, collection, strip_formtastic_options(options), html_options)
  end

  label_options = options_for_label(options).merge(:input_name => input_name)
  label_options[:for] ||= html_options[:id]

  select_html = parts(method, options) do
    select_html
  end

  safe_select_html = ::Formtastic::Util.html_safe(select_html)

  return safe_select_html if input_inline?
  label(method, label_options) << template.(:div, safe_select_html, {:class => 'controls'})
end

#semantic_errors(*args) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/console/formtastic/bootstrap_form_builder.rb', line 56

def semantic_errors(*args)
  html_options = args.extract_options!
  html_options[:class] ||= 'alert alert-error unstyled errors'

  full_errors = args.inject([]) do |array, method|
    attribute = localized_string(method, method.to_sym, :label) || humanized_attribute_name(method)
    @object.errors[method.to_sym].each do |error|
      if error.present?
        error = [attribute, error].join(" ") unless error[0,1] == error[0,1].upcase
        array << error
      end
    end
    array
    #errors = Array(@object.errors[method.to_sym]).to_sentence
    #errors.present? ? array << [attribute, errors].join(" ") : array ||= []
  end
  full_errors << @object.errors[:base] unless html_options.delete(:not) == :base
  full_errors.flatten!
  full_errors.compact!
  return nil if full_errors.blank?
  #html_options[:class] ||= "errors"
  template.(:ul, html_options) do
    ::Formtastic::Util.html_safe(full_errors.map { |error| template.(:li, error) }.join)
  end
end