jgdavey-formtastic 0.2.1

Sign up to get free protection for your applications and to get access to all the features.
data/lib/formtastic.rb ADDED
@@ -0,0 +1,1289 @@
1
+ # Override the default ActiveRecordHelper behaviour of wrapping the input.
2
+ # This gets taken care of semantically by adding an error class to the LI tag
3
+ # containing the input.
4
+ ActionView::Base.field_error_proc = proc do |html_tag, instance_tag|
5
+ html_tag
6
+ end
7
+
8
+ module Formtastic #:nodoc:
9
+
10
+ class SemanticFormBuilder < ActionView::Helpers::FormBuilder
11
+
12
+ @@default_text_field_size = 50
13
+ @@all_fields_required_by_default = true
14
+ @@required_string = proc { %{<abbr title="#{I18n.t 'formtastic.required', :default => 'required'}">*</abbr>} }
15
+ @@optional_string = ''
16
+ @@inline_errors = :sentence
17
+ @@label_str_method = :humanize
18
+ @@collection_label_methods = %w[to_label display_name full_name name title username login value to_s]
19
+ @@inline_order = [ :input, :hints, :errors ]
20
+ @@file_methods = [ :file?, :public_filename ]
21
+ @@priority_countries = ["Australia", "Canada", "United Kingdom", "United States"]
22
+ @@i18n_lookups_by_default = false
23
+
24
+ cattr_accessor :default_text_field_size, :all_fields_required_by_default, :required_string,
25
+ :optional_string, :inline_errors, :label_str_method, :collection_label_methods,
26
+ :inline_order, :file_methods, :priority_countries, :i18n_lookups_by_default
27
+
28
+ I18N_SCOPES = [ '{{model}}.{{action}}.{{attribute}}',
29
+ '{{model}}.{{attribute}}',
30
+ '{{attribute}}']
31
+
32
+ # Keeps simple mappings in a hash
33
+ INPUT_MAPPINGS = {
34
+ :string => :text_field,
35
+ :password => :password_field,
36
+ :numeric => :text_field,
37
+ :text => :text_area,
38
+ :file => :file_field
39
+ }
40
+ STRING_MAPPINGS = [ :string, :password, :numeric ]
41
+
42
+ attr_accessor :template
43
+
44
+ # Returns a suitable form input for the given +method+, using the database column information
45
+ # and other factors (like the method name) to figure out what you probably want.
46
+ #
47
+ # Options:
48
+ #
49
+ # * :as - override the input type (eg force a :string to render as a :password field)
50
+ # * :label - use something other than the method name as the label text, when false no label is printed
51
+ # * :required - specify if the column is required (true) or not (false)
52
+ # * :hint - provide some text to hint or help the user provide the correct information for a field
53
+ # * :input_html - provide options that will be passed down to the generated input
54
+ # * :wrapper_html - provide options that will be passed down to the li wrapper
55
+ #
56
+ # Input Types:
57
+ #
58
+ # Most inputs map directly to one of ActiveRecord's column types by default (eg string_input),
59
+ # but there are a few special cases and some simplification (:integer, :float and :decimal
60
+ # columns all map to a single numeric_input, for example).
61
+ #
62
+ # * :select (a select menu for associations) - default to association names
63
+ # * :check_boxes (a set of check_box inputs for associations) - alternative to :select has_many and has_and_belongs_to_many associations
64
+ # * :radio (a set of radio inputs for associations) - alternative to :select belongs_to associations
65
+ # * :time_zone (a select menu with time zones)
66
+ # * :password (a password input) - default for :string column types with 'password' in the method name
67
+ # * :text (a textarea) - default for :text column types
68
+ # * :date (a date select) - default for :date column types
69
+ # * :datetime (a date and time select) - default for :datetime and :timestamp column types
70
+ # * :time (a time select) - default for :time column types
71
+ # * :boolean (a checkbox) - default for :boolean column types (you can also have booleans as :select and :radio)
72
+ # * :string (a text field) - default for :string column types
73
+ # * :numeric (a text field, like string) - default for :integer, :float and :decimal column types
74
+ # * :country (a select menu of country names) - requires a country_select plugin to be installed
75
+ # * :hidden (a hidden field) - creates a hidden field (added for compatibility)
76
+ #
77
+ # Example:
78
+ #
79
+ # <% semantic_form_for @employee do |form| %>
80
+ # <% form.inputs do -%>
81
+ # <%= form.input :name, :label => "Full Name"%>
82
+ # <%= form.input :manager_id, :as => :radio %>
83
+ # <%= form.input :hired_at, :as => :date, :label => "Date Hired" %>
84
+ # <%= form.input :phone, :required => false, :hint => "Eg: +1 555 1234" %>
85
+ # <% end %>
86
+ # <% end %>
87
+ #
88
+ def input(method, options = {})
89
+ options[:required] = method_required?(method) unless options.key?(:required)
90
+ options[:as] ||= default_input_type(method)
91
+
92
+ html_class = [ options[:as], (options[:required] ? :required : :optional) ]
93
+ html_class << 'error' if @object && @object.respond_to?(:errors) && @object.errors.on(method.to_s)
94
+
95
+ wrapper_html = options.delete(:wrapper_html) || {}
96
+ wrapper_html[:id] ||= generate_html_id(method)
97
+ wrapper_html[:class] = (html_class << wrapper_html[:class]).flatten.compact.join(' ')
98
+
99
+ if [:boolean_select, :boolean_radio].include?(options[:as])
100
+ ::ActiveSupport::Deprecation.warn(":as => :#{options[:as]} is deprecated, use :as => :#{options[:as].to_s[8..-1]} instead", caller[3..-1])
101
+ end
102
+
103
+ list_item_content = @@inline_order.map do |type|
104
+ send(:"inline_#{type}_for", method, options)
105
+ end.compact.join("\n")
106
+
107
+ return template.content_tag(:li, list_item_content, wrapper_html)
108
+ end
109
+
110
+ # Creates an input fieldset and ol tag wrapping for use around a set of inputs. It can be
111
+ # called either with a block (in which you can do the usual Rails form stuff, HTML, ERB, etc),
112
+ # or with a list of fields. These two examples are functionally equivalent:
113
+ #
114
+ # # With a block:
115
+ # <% semantic_form_for @post do |form| %>
116
+ # <% form.inputs do %>
117
+ # <%= form.input :title %>
118
+ # <%= form.input :body %>
119
+ # <% end %>
120
+ # <% end %>
121
+ #
122
+ # # With a list of fields:
123
+ # <% semantic_form_for @post do |form| %>
124
+ # <%= form.inputs :title, :body %>
125
+ # <% end %>
126
+ #
127
+ # # Output:
128
+ # <form ...>
129
+ # <fieldset class="inputs">
130
+ # <ol>
131
+ # <li class="string">...</li>
132
+ # <li class="text">...</li>
133
+ # </ol>
134
+ # </fieldset>
135
+ # </form>
136
+ #
137
+ # === Quick Forms
138
+ #
139
+ # When called without a block or a field list, an input is rendered for each column in the
140
+ # model's database table, just like Rails' scaffolding. You'll obviously want more control
141
+ # than this in a production application, but it's a great way to get started, then come back
142
+ # later to customise the form with a field list or a block of inputs. Example:
143
+ #
144
+ # <% semantic_form_for @post do |form| %>
145
+ # <%= form.inputs %>
146
+ # <% end %>
147
+ #
148
+ # === Options
149
+ #
150
+ # All options (with the exception of :name) are passed down to the fieldset as HTML
151
+ # attributes (id, class, style, etc). If provided, the :name option is passed into a
152
+ # legend tag inside the fieldset (otherwise a legend is not generated).
153
+ #
154
+ # # With a block:
155
+ # <% semantic_form_for @post do |form| %>
156
+ # <% form.inputs :name => "Create a new post", :style => "border:1px;" do %>
157
+ # ...
158
+ # <% end %>
159
+ # <% end %>
160
+ #
161
+ # # With a list (the options must come after the field list):
162
+ # <% semantic_form_for @post do |form| %>
163
+ # <%= form.inputs :title, :body, :name => "Create a new post", :style => "border:1px;" %>
164
+ # <% end %>
165
+ #
166
+ # === It's basically a fieldset!
167
+ #
168
+ # Instead of hard-coding fieldsets & legends into your form to logically group related fields,
169
+ # use inputs:
170
+ #
171
+ # <% semantic_form_for @post do |f| %>
172
+ # <% f.inputs do %>
173
+ # <%= f.input :title %>
174
+ # <%= f.input :body %>
175
+ # <% end %>
176
+ # <% f.inputs :name => "Advanced", :id => "advanced" do %>
177
+ # <%= f.input :created_at %>
178
+ # <%= f.input :user_id, :label => "Author" %>
179
+ # <% end %>
180
+ # <% end %>
181
+ #
182
+ # # Output:
183
+ # <form ...>
184
+ # <fieldset class="inputs">
185
+ # <ol>
186
+ # <li class="string">...</li>
187
+ # <li class="text">...</li>
188
+ # </ol>
189
+ # </fieldset>
190
+ # <fieldset class="inputs" id="advanced">
191
+ # <legend><span>Advanced</span></legend>
192
+ # <ol>
193
+ # <li class="datetime">...</li>
194
+ # <li class="select">...</li>
195
+ # </ol>
196
+ # </fieldset>
197
+ # </form>
198
+ #
199
+ # === Nested attributes
200
+ #
201
+ # As in Rails, you can use semantic_fields_for to nest attributes:
202
+ #
203
+ # <% semantic_form_for @post do |form| %>
204
+ # <%= form.inputs :title, :body %>
205
+ #
206
+ # <% form.semantic_fields_for :author, @bob do |author_form| %>
207
+ # <% author_form.inputs do %>
208
+ # <%= author_form.input :first_name, :required => false %>
209
+ # <%= author_form.input :last_name %>
210
+ # <% end %>
211
+ # <% end %>
212
+ # <% end %>
213
+ #
214
+ # But this does not look formtastic! This is equivalent:
215
+ #
216
+ # <% semantic_form_for @post do |form| %>
217
+ # <%= form.inputs :title, :body %>
218
+ # <% form.inputs :for => [ :author, @bob ] do |author_form| %>
219
+ # <%= author_form.input :first_name, :required => false %>
220
+ # <%= author_form.input :last_name %>
221
+ # <% end %>
222
+ # <% end %>
223
+ #
224
+ # And if you don't need to give options to your input call, you could do it
225
+ # in just one line:
226
+ #
227
+ # <% semantic_form_for @post do |form| %>
228
+ # <%= form.inputs :title, :body %>
229
+ # <%= form.inputs :first_name, :last_name, :for => @bob %>
230
+ # <% end %>
231
+ #
232
+ # Just remember that calling inputs generates a new fieldset to wrap your
233
+ # inputs. If you have two separate models, but, semantically, on the page
234
+ # they are part of the same fieldset, you should use semantic_fields_for
235
+ # instead (just as you would do with Rails' form builder).
236
+ #
237
+ def inputs(*args, &block)
238
+ html_options = args.extract_options!
239
+ html_options[:class] ||= "inputs"
240
+
241
+ if html_options[:for]
242
+ inputs_for_nested_attributes(args, html_options, &block)
243
+ elsif block_given?
244
+ field_set_and_list_wrapping(html_options, &block)
245
+ else
246
+ if @object && args.empty?
247
+ args = @object.class.reflections.map { |n,_| n if _.macro == :belongs_to }
248
+ args += @object.class.content_columns.map(&:name)
249
+ args -= %w[created_at updated_at created_on updated_on lock_version]
250
+ args.compact!
251
+ end
252
+ contents = args.map { |method| input(method.to_sym) }
253
+
254
+ field_set_and_list_wrapping(html_options, contents)
255
+ end
256
+ end
257
+ alias :input_field_set :inputs
258
+
259
+ # Creates a fieldset and ol tag wrapping for form buttons / actions as list items.
260
+ # See inputs documentation for a full example. The fieldset's default class attriute
261
+ # is set to "buttons".
262
+ #
263
+ # See inputs for html attributes and special options.
264
+ def buttons(*args, &block)
265
+ html_options = args.extract_options!
266
+ html_options[:class] ||= "buttons"
267
+
268
+ if block_given?
269
+ field_set_and_list_wrapping(html_options, &block)
270
+ else
271
+ args = [:commit] if args.empty?
272
+ contents = args.map { |button_name| send(:"#{button_name}_button") }
273
+ field_set_and_list_wrapping(html_options, contents)
274
+ end
275
+ end
276
+ alias :button_field_set :buttons
277
+
278
+ # Creates a submit input tag with the value "Save [model name]" (for existing records) or
279
+ # "Create [model name]" (for new records) by default:
280
+ #
281
+ # <%= form.commit_button %> => <input name="commit" type="submit" value="Save Post" />
282
+ #
283
+ # The value of the button text can be overridden:
284
+ #
285
+ # <%= form.commit_button "Go" %> => <input name="commit" type="submit" value="Go" />
286
+ #
287
+ # And you can pass html atributes down to the input, with or without the button text:
288
+ #
289
+ # <%= form.commit_button "Go" %> => <input name="commit" type="submit" value="Go" />
290
+ # <%= form.commit_button :class => "pretty" %> => <input name="commit" type="submit" value="Save Post" class="pretty" />
291
+ #
292
+ # You can use the actual <button/> html tag instead the default <input type="submit"/>:
293
+ #
294
+ # <%= form.commit_button "Save", :use_button_html => true %> => <button name="commit" type="submit">Go</button>
295
+ #
296
+ def commit_button(*args)
297
+ value = args.first.is_a?(String) ? args.shift : save_or_create_button_text
298
+ options = args.shift || {}
299
+ button_html = options.delete(:button_html) || {}
300
+ button_or_input_tag = begin
301
+ if options.delete(:use_button_tag)
302
+ button_html.merge!(:type => 'submit', :name => 'commit')
303
+ template.content_tag(:button, value, button_html)
304
+ else
305
+ self.submit(value, button_html)
306
+ end
307
+ end
308
+ template.content_tag(:li, button_or_input_tag, :class => "commit")
309
+ end
310
+
311
+ # A thin wrapper around #fields_for to set :builder => Formtastic::SemanticFormBuilder
312
+ # for nesting forms:
313
+ #
314
+ # # Example:
315
+ # <% semantic_form_for @post do |post| %>
316
+ # <% post.semantic_fields_for :author do |author| %>
317
+ # <% author.inputs :name %>
318
+ # <% end %>
319
+ # <% end %>
320
+ #
321
+ # # Output:
322
+ # <form ...>
323
+ # <fieldset class="inputs">
324
+ # <ol>
325
+ # <li class="string"><input type='text' name='post[author][name]' id='post_author_name' /></li>
326
+ # </ol>
327
+ # </fieldset>
328
+ # </form>
329
+ #
330
+ def semantic_fields_for(record_or_name_or_array, *args, &block)
331
+ opts = args.extract_options!
332
+ opts.merge!(:builder => Formtastic::SemanticFormBuilder)
333
+ args.push(opts)
334
+ fields_for(record_or_name_or_array, *args, &block)
335
+ end
336
+
337
+ # Generates the label for the input. It also accepts the same arguments as
338
+ # Rails label method. It has three options that are not supported by Rails
339
+ # label method:
340
+ #
341
+ # * :required - Appends an abbr tag if :required is true
342
+ # * :label - An alternative form to give the label content. Whenever label
343
+ # is false, a blank string is returned.
344
+ # * :as_span - When true returns a span tag with class label instead of a label element
345
+ # * :input_name - Gives the input to match for. This is needed when you want to
346
+ # to call f.label :authors but it should match :author_ids.
347
+ #
348
+ # == Examples
349
+ #
350
+ # f.label :title # like in rails, except that it searches the label on I18n API too
351
+ #
352
+ # f.label :title, "Your post title"
353
+ # f.label :title, :label => "Your post title" # Added for formtastic API
354
+ #
355
+ # f.label :title, :required => true # Returns <label>Title<abbr title="required">*</abbr></label>
356
+ #
357
+ def label(method, options_or_text=nil, options=nil)
358
+ if options_or_text.is_a?(Hash)
359
+ return if options_or_text[:label] == false
360
+ options = options_or_text
361
+ text = options.delete(:label)
362
+ else
363
+ text = options_or_text
364
+ options ||= {}
365
+ end
366
+
367
+ text = localized_attribute_string(method, text, :label)
368
+ text ||= humanized_attribute_name(method)
369
+ text << required_or_optional_string(options.delete(:required))
370
+
371
+ input_name = options.delete(:input_name) || method
372
+ if options.delete(:as_span)
373
+ options[:class] ||= 'label'
374
+ template.content_tag(:span, text, options)
375
+ else
376
+ super(input_name, text, options)
377
+ end
378
+ end
379
+
380
+ # Generates error messages for the given method. Errors can be shown as list
381
+ # or as sentence. If :none is set, no error is shown.
382
+ #
383
+ # This method is also aliased as errors_on, so you can call on your custom
384
+ # inputs as well:
385
+ #
386
+ # semantic_form_for :post do |f|
387
+ # f.text_field(:body)
388
+ # f.errors_on(:body)
389
+ # end
390
+ #
391
+ def inline_errors_for(method, options=nil) #:nodoc:
392
+ return nil unless @object && @object.respond_to?(:errors) && [:sentence, :list].include?(@@inline_errors)
393
+
394
+ errors = @object.errors.on(method.to_s)
395
+ send("error_#{@@inline_errors}", Array(errors)) unless errors.blank?
396
+ end
397
+ alias :errors_on :inline_errors_for
398
+
399
+ protected
400
+
401
+ # Deals with :for option when it's supplied to inputs methods. Additional
402
+ # options to be passed down to :for should be supplied using :for_options
403
+ # key.
404
+ #
405
+ # It should raise an error if a block with arity zero is given.
406
+ #
407
+ def inputs_for_nested_attributes(args, options, &block)
408
+ args << options.merge!(:parent => { :builder => self, :for => options[:for] })
409
+
410
+ fields_for_block = if block_given?
411
+ raise ArgumentError, 'You gave :for option with a block to inputs method, ' <<
412
+ 'but the block does not accept any argument.' if block.arity <= 0
413
+
414
+ proc { |f| f.inputs(*args){ block.call(f) } }
415
+ else
416
+ proc { |f| f.inputs(*args) }
417
+ end
418
+
419
+ fields_for_args = [options.delete(:for), options.delete(:for_options) || {}].flatten
420
+ semantic_fields_for(*fields_for_args, &fields_for_block)
421
+ end
422
+
423
+ # Remove any Formtastic-specific options before passing the down options.
424
+ #
425
+ def set_options(options)
426
+ options.except(:value_method, :label_method, :collection, :required, :label,
427
+ :as, :hint, :input_html, :label_html, :value_as_class)
428
+ end
429
+
430
+ # Create a default button text. If the form is working with a object, it
431
+ # defaults to "Create model" or "Save model" depending if we are working
432
+ # with a new_record or not.
433
+ #
434
+ # When not working with models, it defaults to "Submit object".
435
+ #
436
+ def save_or_create_button_text(prefix='Submit') #:nodoc:
437
+ if @object
438
+ prefix = @object.new_record? ? 'Create' : 'Save'
439
+ object_name = @object.class.human_name
440
+ else
441
+ object_name = @object_name.to_s.send(@@label_str_method)
442
+ end
443
+
444
+ I18n.t(prefix.downcase, :default => prefix, :scope => [:formtastic]) << ' ' << object_name
445
+ end
446
+
447
+ # Determins if the attribute (eg :title) should be considered required or not.
448
+ #
449
+ # * if the :required option was provided in the options hash, the true/false value will be
450
+ # returned immediately, allowing the view to override any guesswork that follows:
451
+ #
452
+ # * if the :required option isn't provided in the options hash, and the ValidationReflection
453
+ # plugin is installed (http://github.com/redinger/validation_reflection), true is returned
454
+ # if the validates_presence_of macro has been used in the class for this attribute, or false
455
+ # otherwise.
456
+ #
457
+ # * if the :required option isn't provided, and the plugin isn't available, the value of the
458
+ # configuration option @@all_fields_required_by_default is used.
459
+ #
460
+ def method_required?(attribute) #:nodoc:
461
+ if @object && @object.class.respond_to?(:reflect_on_all_validations)
462
+ attribute_sym = attribute.to_s.sub(/_id$/, '').to_sym
463
+
464
+ @object.class.reflect_on_all_validations.any? do |validation|
465
+ validation.macro == :validates_presence_of && validation.name == attribute_sym
466
+ end
467
+ else
468
+ @@all_fields_required_by_default
469
+ end
470
+ end
471
+
472
+ # A method that deals with most of inputs (:string, :password, :file,
473
+ # :textarea and :numeric). :select, :radio, :boolean and :datetime inputs
474
+ # are not handled by this method, since they need more detailed approach.
475
+ #
476
+ # If input_html is given as option, it's passed down to the input.
477
+ #
478
+ def input_simple(type, method, options)
479
+ html_options = options.delete(:input_html) || {}
480
+ html_options = default_string_options(method, type).merge(html_options) if STRING_MAPPINGS.include?(type)
481
+
482
+ self.label(method, options.slice(:label, :required)) +
483
+ self.send(INPUT_MAPPINGS[type], method, html_options)
484
+ end
485
+
486
+ # Outputs a hidden field inside the wrapper, which should be hidden with CSS.
487
+ # Additionals options can be given and will be sent straight to hidden input
488
+ # element.
489
+ #
490
+ def hidden_input(method, options)
491
+ self.hidden_field(method, set_options(options))
492
+ end
493
+
494
+ # Outputs a label and a select box containing options from the parent
495
+ # (belongs_to, has_many, has_and_belongs_to_many) association. If an association
496
+ # is has_many or has_and_belongs_to_many the select box will be set as multi-select
497
+ # and size = 5
498
+ #
499
+ # Example (belongs_to):
500
+ #
501
+ # f.input :author
502
+ #
503
+ # <label for="book_author_id">Author</label>
504
+ # <select id="book_author_id" name="book[author_id]">
505
+ # <option value=""></option>
506
+ # <option value="1">Justin French</option>
507
+ # <option value="2">Jane Doe</option>
508
+ # </select>
509
+ #
510
+ # Example (has_many):
511
+ #
512
+ # f.input :chapters
513
+ #
514
+ # <label for="book_chapter_ids">Chapters</label>
515
+ # <select id="book_chapter_ids" name="book[chapter_ids]">
516
+ # <option value=""></option>
517
+ # <option value="1">Chapter 1</option>
518
+ # <option value="2">Chapter 2</option>
519
+ # </select>
520
+ #
521
+ # Example (has_and_belongs_to_many):
522
+ #
523
+ # f.input :authors
524
+ #
525
+ # <label for="book_author_ids">Authors</label>
526
+ # <select id="book_author_ids" name="book[author_ids]">
527
+ # <option value=""></option>
528
+ # <option value="1">Justin French</option>
529
+ # <option value="2">Jane Doe</option>
530
+ # </select>
531
+ #
532
+ #
533
+ # You can customize the options available in the select by passing in a collection (an Array or
534
+ # Hash) through the :collection option. If not provided, the choices are found by inferring the
535
+ # parent's class name from the method name and simply calling find(:all) on it
536
+ # (VehicleOwner.find(:all) in the example above).
537
+ #
538
+ # Examples:
539
+ #
540
+ # f.input :author, :collection => @authors
541
+ # f.input :author, :collection => Author.find(:all)
542
+ # f.input :author, :collection => [@justin, @kate]
543
+ # f.input :author, :collection => {@justin.name => @justin.id, @kate.name => @kate.id}
544
+ # f.input :author, :collection => ["Justin", "Kate", "Amelia", "Gus", "Meg"]
545
+ #
546
+ # Note: This input looks for a label method in the parent association.
547
+ #
548
+ # You can customize the text label inside each option tag, by naming the correct method
549
+ # (:full_name, :display_name, :account_number, etc) to call on each object in the collection
550
+ # by passing in the :label_method option. By default the :label_method is whichever element of
551
+ # Formtastic::SemanticFormBuilder.collection_label_methods is found first.
552
+ #
553
+ # Examples:
554
+ #
555
+ # f.input :author, :label_method => :full_name
556
+ # f.input :author, :label_method => :display_name
557
+ # f.input :author, :label_method => :to_s
558
+ # f.input :author, :label_method => :label
559
+ #
560
+ # You can also customize the value inside each option tag, by passing in the :value_method option.
561
+ # Usage is the same as the :label_method option
562
+ #
563
+ # Examples:
564
+ #
565
+ # f.input :author, :value_method => :full_name
566
+ # f.input :author, :value_method => :display_name
567
+ # f.input :author, :value_method => :to_s
568
+ # f.input :author, :value_method => :value
569
+ #
570
+ # You can pass html_options to the select tag using :input_html => {}
571
+ #
572
+ # Examples:
573
+ #
574
+ # f.input :authors, :input_html => {:size => 20, :multiple => true}
575
+ #
576
+ # By default, all select inputs will have a blank option at the top of the list. You can add
577
+ # a prompt with the :prompt option, or disable the blank option with :include_blank => false.
578
+ #
579
+ def select_input(method, options)
580
+ collection = find_collection_for_column(method, options)
581
+ html_options = options.delete(:input_html) || {}
582
+
583
+ unless options.key?(:include_blank) || options.key?(:prompt)
584
+ options[:include_blank] = true
585
+ end
586
+
587
+ reflection = find_reflection(method)
588
+ if reflection && [ :has_many, :has_and_belongs_to_many ].include?(reflection.macro)
589
+ options[:include_blank] = false
590
+ html_options[:multiple] ||= true
591
+ html_options[:size] ||= 5
592
+ end
593
+
594
+ input_name = generate_association_input_name(method)
595
+ self.label(method, options.slice(:label, :required).merge(:input_name => input_name)) +
596
+ self.select(input_name, collection, set_options(options), html_options)
597
+ end
598
+ alias :boolean_select_input :select_input
599
+
600
+ # Outputs a timezone select input as Rails' time_zone_select helper. You
601
+ # can give priority zones as option.
602
+ #
603
+ # Examples:
604
+ #
605
+ # f.input :time_zone, :as => :time_zone, :priority_zones => /Australia/
606
+ #
607
+ def time_zone_input(method, options)
608
+ html_options = options.delete(:input_html) || {}
609
+
610
+ self.label(method, options.slice(:label, :required)) +
611
+ self.time_zone_select(method, options.delete(:priority_zones), set_options(options), html_options)
612
+ end
613
+
614
+ # Outputs a fieldset containing a legend for the label text, and an ordered list (ol) of list
615
+ # items, one for each possible choice in the belongs_to association. Each li contains a
616
+ # label and a radio input.
617
+ #
618
+ # Example:
619
+ #
620
+ # f.input :author, :as => :radio
621
+ #
622
+ # Output:
623
+ #
624
+ # <fieldset>
625
+ # <legend><span>Author</span></legend>
626
+ # <ol>
627
+ # <li>
628
+ # <label for="book_author_id_1"><input id="book_author_id_1" name="book[author_id]" type="radio" value="1" /> Justin French</label>
629
+ # </li>
630
+ # <li>
631
+ # <label for="book_author_id_2"><input id="book_author_id_2" name="book[owner_id]" type="radio" value="2" /> Kate French</label>
632
+ # </li>
633
+ # </ol>
634
+ # </fieldset>
635
+ #
636
+ # You can customize the options available in the select by passing in a collection (an Array or
637
+ # Hash) through the :collection option. If not provided, the choices are found by inferring the
638
+ # parent's class name from the method name and simply calling find(:all) on it
639
+ # (Author.find(:all) in the example above).
640
+ #
641
+ # Examples:
642
+ #
643
+ # f.input :author, :as => :radio, :collection => @authors
644
+ # f.input :author, :as => :radio, :collection => Author.find(:all)
645
+ # f.input :author, :as => :radio, :collection => [@justin, @kate]
646
+ # f.input :author, :collection => ["Justin", "Kate", "Amelia", "Gus", "Meg"]
647
+ #
648
+ # You can also customize the text label inside each option tag, by naming the correct method
649
+ # (:full_name, :display_name, :account_number, etc) to call on each object in the collection
650
+ # by passing in the :label_method option. By default the :label_method is whichever element of
651
+ # Formtastic::SemanticFormBuilder.collection_label_methods is found first.
652
+ #
653
+ # Examples:
654
+ #
655
+ # f.input :author, :as => :radio, :label_method => :full_name
656
+ # f.input :author, :as => :radio, :label_method => :display_name
657
+ # f.input :author, :as => :radio, :label_method => :to_s
658
+ # f.input :author, :as => :radio, :label_method => :label
659
+ #
660
+ # Finally, you can set :value_as_class => true if you want that LI wrappers
661
+ # contains a class with the wrapped radio input value.
662
+ #
663
+ def radio_input(method, options)
664
+ collection = find_collection_for_column(method, options)
665
+ html_options = set_options(options).merge(options.delete(:input_html) || {})
666
+
667
+ input_name = generate_association_input_name(method)
668
+ value_as_class = options.delete(:value_as_class)
669
+
670
+ list_item_content = collection.map do |c|
671
+ label = c.is_a?(Array) ? c.first : c
672
+ value = c.is_a?(Array) ? c.last : c
673
+
674
+ li_content = template.content_tag(:label,
675
+ "#{self.radio_button(input_name, value, html_options)} #{label}",
676
+ :for => generate_html_id(input_name, value.to_s.downcase)
677
+ )
678
+
679
+ li_options = value_as_class ? { :class => value.to_s.downcase } : {}
680
+ template.content_tag(:li, li_content, li_options)
681
+ end
682
+
683
+ field_set_and_list_wrapping_for_method(method, options, list_item_content)
684
+ end
685
+ alias :boolean_radio_input :radio_input
686
+
687
+ # Outputs a fieldset with a legend for the method label, and a ordered list (ol) of list
688
+ # items (li), one for each fragment for the date (year, month, day). Each li contains a label
689
+ # (eg "Year") and a select box. See date_or_datetime_input for a more detailed output example.
690
+ #
691
+ # Some of Rails' options for select_date are supported, but not everything yet.
692
+ def date_input(method, options)
693
+ date_or_datetime_input(method, options.merge(:discard_hour => true))
694
+ end
695
+
696
+
697
+ # Outputs a fieldset with a legend for the method label, and a ordered list (ol) of list
698
+ # items (li), one for each fragment for the date (year, month, day, hour, min, sec). Each li
699
+ # contains a label (eg "Year") and a select box. See date_or_datetime_input for a more
700
+ # detailed output example.
701
+ #
702
+ # Some of Rails' options for select_date are supported, but not everything yet.
703
+ def datetime_input(method, options)
704
+ date_or_datetime_input(method, options)
705
+ end
706
+
707
+
708
+ # Outputs a fieldset with a legend for the method label, and a ordered list (ol) of list
709
+ # items (li), one for each fragment for the time (hour, minute, second). Each li contains a label
710
+ # (eg "Hour") and a select box. See date_or_datetime_input for a more detailed output example.
711
+ #
712
+ # Some of Rails' options for select_time are supported, but not everything yet.
713
+ def time_input(method, options)
714
+ date_or_datetime_input(method, options.merge(:discard_year => true, :discard_month => true, :discard_day => true))
715
+ end
716
+
717
+
718
+ # <fieldset>
719
+ # <legend>Created At</legend>
720
+ # <ol>
721
+ # <li>
722
+ # <label for="user_created_at_1i">Year</label>
723
+ # <select id="user_created_at_1i" name="user[created_at(1i)]">
724
+ # <option value="2003">2003</option>
725
+ # ...
726
+ # <option value="2013">2013</option>
727
+ # </select>
728
+ # </li>
729
+ # <li>
730
+ # <label for="user_created_at_2i">Month</label>
731
+ # <select id="user_created_at_2i" name="user[created_at(2i)]">
732
+ # <option value="1">January</option>
733
+ # ...
734
+ # <option value="12">December</option>
735
+ # </select>
736
+ # </li>
737
+ # <li>
738
+ # <label for="user_created_at_3i">Day</label>
739
+ # <select id="user_created_at_3i" name="user[created_at(3i)]">
740
+ # <option value="1">1</option>
741
+ # ...
742
+ # <option value="31">31</option>
743
+ # </select>
744
+ # </li>
745
+ # </ol>
746
+ # </fieldset>
747
+ #
748
+ # This is an absolute abomination, but so is the official Rails select_date().
749
+ #
750
+ def date_or_datetime_input(method, options)
751
+ position = { :year => 1, :month => 2, :day => 3, :hour => 4, :minute => 5, :second => 6 }
752
+ inputs = options.delete(:order) || I18n.translate(:'date.order') || [:year, :month, :day]
753
+
754
+ time_inputs = [:hour, :minute]
755
+ time_inputs << [:second] if options[:include_seconds]
756
+
757
+ list_items_capture = ""
758
+ hidden_fields_capture = ""
759
+
760
+ # Gets the datetime object. It can be a Fixnum, Date or Time, or nil.
761
+ datetime = @object ? @object.send(method) : nil
762
+ html_options = options.delete(:input_html) || {}
763
+
764
+ (inputs + time_inputs).each do |input|
765
+ html_id = generate_html_id(method, "#{position[input]}i")
766
+ field_name = "#{method}(#{position[input]}i)"
767
+ if options["discard_#{input}".intern]
768
+ break if time_inputs.include?(input)
769
+
770
+ hidden_value = datetime.respond_to?(input) ? datetime.send(input) : datetime
771
+ hidden_fields_capture << template.hidden_field_tag("#{@object_name}[#{field_name}]", (hidden_value || 1), :id => html_id)
772
+ else
773
+ opts = set_options(options).merge(:prefix => @object_name, :field_name => field_name)
774
+ item_label_text = I18n.t(input.to_s, :default => input.to_s.humanize, :scope => [:datetime, :prompts])
775
+
776
+ list_items_capture << template.content_tag(:li,
777
+ template.content_tag(:label, item_label_text, :for => html_id) +
778
+ template.send("select_#{input}".intern, datetime, opts, html_options.merge(:id => html_id))
779
+ )
780
+ end
781
+ end
782
+
783
+ hidden_fields_capture + field_set_and_list_wrapping_for_method(method, options, list_items_capture)
784
+ end
785
+
786
+
787
+ # Outputs a fieldset containing a legend for the label text, and an ordered list (ol) of list
788
+ # items, one for each possible choice in the belongs_to association. Each li contains a
789
+ # label and a check_box input.
790
+ #
791
+ # This is an alternative for has many and has and belongs to many associations.
792
+ #
793
+ # Example:
794
+ #
795
+ # f.input :author, :as => :check_boxes
796
+ #
797
+ # Output:
798
+ #
799
+ # <fieldset>
800
+ # <legend><span>Authors</span></legend>
801
+ # <ol>
802
+ # <li>
803
+ # <input type="hidden" name="book[author_id][1]" value="">
804
+ # <label for="book_author_id_1"><input id="book_author_id_1" name="book[author_id][1]" type="checkbox" value="1" /> Justin French</label>
805
+ # </li>
806
+ # <li>
807
+ # <input type="hidden" name="book[author_id][2]" value="">
808
+ # <label for="book_author_id_2"><input id="book_author_id_2" name="book[owner_id][2]" type="checkbox" value="2" /> Kate French</label>
809
+ # </li>
810
+ # </ol>
811
+ # </fieldset>
812
+ #
813
+ # Notice that the value of the checkbox is the same as the id and the hidden
814
+ # field has empty value. You can override the hidden field value using the
815
+ # unchecked_value option.
816
+ #
817
+ # You can customize the options available in the set by passing in a collection (Array) of
818
+ # ActiveRecord objects through the :collection option. If not provided, the choices are found
819
+ # by inferring the parent's class name from the method name and simply calling find(:all) on
820
+ # it (Author.find(:all) in the example above).
821
+ #
822
+ # Examples:
823
+ #
824
+ # f.input :author, :as => :check_boxes, :collection => @authors
825
+ # f.input :author, :as => :check_boxes, :collection => Author.find(:all)
826
+ # f.input :author, :as => :check_boxes, :collection => [@justin, @kate]
827
+ #
828
+ # You can also customize the text label inside each option tag, by naming the correct method
829
+ # (:full_name, :display_name, :account_number, etc) to call on each object in the collection
830
+ # by passing in the :label_method option. By default the :label_method is whichever element of
831
+ # Formtastic::SemanticFormBuilder.collection_label_methods is found first.
832
+ #
833
+ # Examples:
834
+ #
835
+ # f.input :author, :as => :check_boxes, :label_method => :full_name
836
+ # f.input :author, :as => :check_boxes, :label_method => :display_name
837
+ # f.input :author, :as => :check_boxes, :label_method => :to_s
838
+ # f.input :author, :as => :check_boxes, :label_method => :label
839
+ #
840
+ # You can set :value_as_class => true if you want that LI wrappers contains
841
+ # a class with the wrapped checkbox input value.
842
+ #
843
+ def check_boxes_input(method, options)
844
+ collection = find_collection_for_column(method, options)
845
+ html_options = options.delete(:input_html) || {}
846
+
847
+ input_name = generate_association_input_name(method)
848
+ value_as_class = options.delete(:value_as_class)
849
+ unchecked_value = options.delete(:unchecked_value) || ''
850
+ html_options = { :name => "#{@object_name}[#{input_name}][]" }.merge(html_options)
851
+
852
+ list_item_content = collection.map do |c|
853
+ label = c.is_a?(Array) ? c.first : c
854
+ value = c.is_a?(Array) ? c.last : c
855
+
856
+ html_options.merge!(:id => generate_html_id(input_name, value.to_s.downcase))
857
+
858
+ li_content = template.content_tag(:label,
859
+ "#{self.check_box(input_name, html_options, value, unchecked_value)} #{label}",
860
+ :for => html_options[:id]
861
+ )
862
+
863
+ li_options = value_as_class ? { :class => value.to_s.downcase } : {}
864
+ template.content_tag(:li, li_content, li_options)
865
+ end
866
+
867
+ field_set_and_list_wrapping_for_method(method, options, list_item_content)
868
+ end
869
+
870
+
871
+ # Outputs a country select input, wrapping around a regular country_select helper.
872
+ # Rails doesn't come with a country_select helper by default any more, so you'll need to install
873
+ # the "official" plugin, or, if you wish, any other country_select plugin that behaves in the
874
+ # same way.
875
+ #
876
+ # The Rails plugin iso-3166-country-select plugin can be found "here":http://github.com/rails/iso-3166-country-select.
877
+ #
878
+ # By default, Formtastic includes a handfull of english-speaking countries as "priority counties",
879
+ # which you can change to suit your market and user base (see README for more info on config).
880
+ #
881
+ # Examples:
882
+ # f.input :location, :as => :country # use Formtastic::SemanticFormBuilder.priority_countries array for the priority countries
883
+ # f.input :location, :as => :country, :priority_countries => /Australia/ # set your own
884
+ #
885
+ def country_input(method, options)
886
+ raise "To use the :country input, please install a country_select plugin, like this one: http://github.com/rails/iso-3166-country-select" unless self.respond_to?(:country_select)
887
+
888
+ html_options = options.delete(:input_html) || {}
889
+ priority_countries = options.delete(:priority_countries) || @@priority_countries
890
+
891
+ self.label(method, options.slice(:label, :required)) +
892
+ self.country_select(method, priority_countries, set_options(options), html_options)
893
+ end
894
+
895
+
896
+ # Outputs a label containing a checkbox and the label text. The label defaults
897
+ # to the column name (method name) and can be altered with the :label option.
898
+ # :checked_value and :unchecked_value options are also available.
899
+ #
900
+ def boolean_input(method, options)
901
+ html_options = options.delete(:input_html) || {}
902
+
903
+ input = self.check_box(method, set_options(options).merge(html_options),
904
+ options.delete(:checked_value) || '1', options.delete(:unchecked_value) || '0')
905
+
906
+ label = options.delete(:label) || humanized_attribute_name(method)
907
+ self.label(method, input + label, options.slice(:required))
908
+ end
909
+
910
+ # Generates an input for the given method using the type supplied with :as.
911
+ #
912
+ # If the input is included in INPUT_MAPPINGS, it uses input_simple
913
+ # implementation which maps most of the inputs. All others have specific
914
+ # code and then a proper handler should be called (like radio_input) for
915
+ # :radio types.
916
+ #
917
+ def inline_input_for(method, options)
918
+ input_type = options.delete(:as)
919
+
920
+ if INPUT_MAPPINGS.key?(input_type)
921
+ input_simple(input_type, method, options)
922
+ else
923
+ send("#{input_type}_input", method, options)
924
+ end
925
+ end
926
+
927
+ # Generates hints for the given method using the text supplied in :hint.
928
+ #
929
+ def inline_hints_for(method, options) #:nodoc:
930
+ options[:hint] = localized_attribute_string(method, options[:hint], :hint)
931
+ return if options[:hint].blank?
932
+ template.content_tag(:p, options[:hint], :class => 'inline-hints')
933
+ end
934
+
935
+ # Creates an error sentence by calling to_sentence on the errors array.
936
+ #
937
+ def error_sentence(errors) #:nodoc:
938
+ template.content_tag(:p, errors.to_sentence.untaint, :class => 'inline-errors')
939
+ end
940
+
941
+ # Creates an error li list.
942
+ #
943
+ def error_list(errors) #:nodoc:
944
+ list_elements = []
945
+ errors.each do |error|
946
+ list_elements << template.content_tag(:li, error.untaint)
947
+ end
948
+ template.content_tag(:ul, list_elements.join("\n"), :class => 'errors')
949
+ end
950
+
951
+ # Generates the required or optional string. If the value set is a proc,
952
+ # it evaluates the proc first.
953
+ #
954
+ def required_or_optional_string(required) #:nodoc:
955
+ string_or_proc = case required
956
+ when true
957
+ @@required_string
958
+ when false
959
+ @@optional_string
960
+ else
961
+ required
962
+ end
963
+
964
+ if string_or_proc.is_a?(Proc)
965
+ string_or_proc.call
966
+ else
967
+ string_or_proc.to_s
968
+ end
969
+ end
970
+
971
+ # Generates a fieldset and wraps the content in an ordered list. When working
972
+ # with nested attributes (in Rails 2.3), it allows %i as interpolation option
973
+ # in :name. So you can do:
974
+ #
975
+ # f.inputs :name => 'Task #%i', :for => :tasks
976
+ #
977
+ # And it will generate a fieldset for each task with legend 'Task #1', 'Task #2',
978
+ # 'Task #3' and so on.
979
+ #
980
+ def field_set_and_list_wrapping(html_options, contents='', &block) #:nodoc:
981
+ legend = html_options.delete(:name).to_s
982
+ legend %= parent_child_index(html_options[:parent]) if html_options[:parent]
983
+ legend = template.content_tag(:legend, template.content_tag(:span, legend)) unless legend.blank?
984
+
985
+ contents = template.capture(&block) if block_given?
986
+
987
+ # Ruby 1.9: String#to_s behavior changed, need to make an explicit join.
988
+ contents = contents.join if contents.respond_to?(:join)
989
+ fieldset = template.content_tag(:fieldset,
990
+ legend + template.content_tag(:ol, contents),
991
+ html_options.except(:builder, :parent)
992
+ )
993
+
994
+ template.concat(fieldset) if block_given?
995
+ fieldset
996
+ end
997
+
998
+ # Also generates a fieldset and an ordered list but with label based in
999
+ # method. This methods is currently used by radio and datetime inputs.
1000
+ #
1001
+ def field_set_and_list_wrapping_for_method(method, options, contents)
1002
+ contents = contents.join if contents.respond_to?(:join)
1003
+
1004
+ template.content_tag(:fieldset,
1005
+ %{<legend>#{self.label(method, options.slice(:label, :required).merge!(:as_span => true))}</legend>} +
1006
+ template.content_tag(:ol, contents)
1007
+ )
1008
+ end
1009
+
1010
+ # For methods that have a database column, take a best guess as to what the input method
1011
+ # should be. In most cases, it will just return the column type (eg :string), but for special
1012
+ # cases it will simplify (like the case of :integer, :float & :decimal to :numeric), or do
1013
+ # something different (like :password and :select).
1014
+ #
1015
+ # If there is no column for the method (eg "virtual columns" with an attr_accessor), the
1016
+ # default is a :string, a similar behaviour to Rails' scaffolding.
1017
+ #
1018
+ def default_input_type(method) #:nodoc:
1019
+ column = @object.column_for_attribute(method) if @object.respond_to?(:column_for_attribute)
1020
+
1021
+ if column
1022
+ # handle the special cases where the column type doesn't map to an input method
1023
+ return :time_zone if column.type == :string && method.to_s =~ /time_zone/
1024
+ return :select if column.type == :integer && method.to_s =~ /_id$/
1025
+ return :datetime if column.type == :timestamp
1026
+ return :numeric if [:integer, :float, :decimal].include?(column.type)
1027
+ return :password if column.type == :string && method.to_s =~ /password/
1028
+ return :country if column.type == :string && method.to_s =~ /country/
1029
+
1030
+ # otherwise assume the input name will be the same as the column type (eg string_input)
1031
+ return column.type
1032
+ else
1033
+ if @object
1034
+ return :select if find_reflection(method)
1035
+
1036
+ file = @object.send(method) if @object.respond_to?(method)
1037
+ return :file if file && @@file_methods.any? { |m| file.respond_to?(m) }
1038
+ end
1039
+
1040
+ return :password if method.to_s =~ /password/
1041
+ return :string
1042
+ end
1043
+ end
1044
+
1045
+ # Used by select and radio inputs. The collection can be retrieved by
1046
+ # three ways:
1047
+ #
1048
+ # * Explicitly provided through :collection
1049
+ # * Retrivied through an association
1050
+ # * Or a boolean column, which will generate a localized { "Yes" => true, "No" => false } hash.
1051
+ #
1052
+ # If the collection is not a hash or an array of strings, fixnums or arrays,
1053
+ # we use label_method and value_method to retreive an array with the
1054
+ # appropriate label and value.
1055
+ #
1056
+ def find_collection_for_column(column, options)
1057
+ reflection = find_reflection(column)
1058
+
1059
+ collection = if options[:collection]
1060
+ options.delete(:collection)
1061
+ elsif reflection || column.to_s =~ /_id$/
1062
+ parent_class = if reflection
1063
+ reflection.klass
1064
+ else
1065
+ ::ActiveSupport::Deprecation.warn("The _id way of doing things is deprecated. Please use the association method (#{column.to_s.sub(/_id$/,'')})", caller[3..-1])
1066
+ column.to_s.sub(/_id$/,'').camelize.constantize
1067
+ end
1068
+
1069
+ parent_class.find(:all)
1070
+ else
1071
+ create_boolean_collection(options)
1072
+ end
1073
+
1074
+ collection = collection.to_a if collection.instance_of?(Hash)
1075
+
1076
+ # Return if we have an Array of strings, fixnums or arrays
1077
+ return collection if collection.instance_of?(Array) &&
1078
+ [Array, Fixnum, String, Symbol].include?(collection.first.class)
1079
+
1080
+ label = options.delete(:label_method) || detect_label_method(collection)
1081
+ value = options.delete(:value_method) || :id
1082
+
1083
+ collection.map { |o| [o.send(label), o.send(value)] }
1084
+ end
1085
+
1086
+ # Detected the label collection method when none is supplied using the
1087
+ # values set in @@collection_label_methods.
1088
+ #
1089
+ def detect_label_method(collection) #:nodoc:
1090
+ @@collection_label_methods.detect { |m| collection.first.respond_to?(m) }
1091
+ end
1092
+
1093
+ # Returns a hash to be used by radio and select inputs when a boolean field
1094
+ # is provided.
1095
+ #
1096
+ def create_boolean_collection(options)
1097
+ options[:true] ||= I18n.t('yes', :default => 'Yes', :scope => [:formtastic])
1098
+ options[:false] ||= I18n.t('no', :default => 'No', :scope => [:formtastic])
1099
+ options[:value_as_class] = true unless options.key?(:value_as_class)
1100
+
1101
+ [ [ options.delete(:true), true], [ options.delete(:false), false ] ]
1102
+ end
1103
+
1104
+ # Used by association inputs (select, radio) to generate the name that should
1105
+ # be used for the input
1106
+ #
1107
+ # belongs_to :author; f.input :author; will generate 'author_id'
1108
+ # belongs_to :entity, :foreign_key = :owner_id; f.input :author; will generate 'owner_id'
1109
+ # has_many :authors; f.input :authors; will generate 'author_ids'
1110
+ # has_and_belongs_to_many will act like has_many
1111
+ #
1112
+ def generate_association_input_name(method)
1113
+ if reflection = find_reflection(method)
1114
+ if [:has_and_belongs_to_many, :has_many].include?(reflection.macro)
1115
+ "#{method.to_s.singularize}_ids"
1116
+ else
1117
+ reflection.options[:foreign_key] || "#{method}_id"
1118
+ end
1119
+ else
1120
+ method
1121
+ end
1122
+ end
1123
+
1124
+ # If an association method is passed in (f.input :author) try to find the
1125
+ # reflection object.
1126
+ #
1127
+ def find_reflection(method)
1128
+ @object.class.reflect_on_association(method) if @object.class.respond_to?(:reflect_on_association)
1129
+ end
1130
+
1131
+ # Generates default_string_options by retrieving column information from
1132
+ # the database.
1133
+ #
1134
+ def default_string_options(method, type) #:nodoc:
1135
+ column = @object.column_for_attribute(method) if @object.respond_to?(:column_for_attribute)
1136
+
1137
+ if type == :numeric || column.nil? || column.limit.nil?
1138
+ { :size => @@default_text_field_size }
1139
+ else
1140
+ { :maxlength => column.limit, :size => [column.limit, @@default_text_field_size].min }
1141
+ end
1142
+ end
1143
+
1144
+ # Generate the html id for the li tag.
1145
+ # It takes into account options[:index] and @auto_index to generate li
1146
+ # elements with appropriate index scope. It also sanitizes the object
1147
+ # and method names.
1148
+ #
1149
+ def generate_html_id(method_name, value='input')
1150
+ if options.has_key?(:index)
1151
+ index = "_#{options[:index]}"
1152
+ elsif defined?(@auto_index)
1153
+ index = "_#{@auto_index}"
1154
+ else
1155
+ index = ""
1156
+ end
1157
+ sanitized_method_name = method_name.to_s.gsub(/[\?\/\-]$/, '')
1158
+
1159
+ "#{sanitized_object_name}#{index}_#{sanitized_method_name}_#{value}"
1160
+ end
1161
+
1162
+ # Gets the nested_child_index value from the parent builder. In Rails 2.3
1163
+ # it always returns a fixnum. In next versions it returns a hash with each
1164
+ # association that the parent builds.
1165
+ #
1166
+ def parent_child_index(parent)
1167
+ duck = parent[:builder].instance_variable_get('@nested_child_index')
1168
+
1169
+ if duck.is_a?(Hash)
1170
+ child = parent[:for]
1171
+ child = child.first if child.respond_to?(:first)
1172
+ duck[child].to_i + 1
1173
+ else
1174
+ duck.to_i + 1
1175
+ end
1176
+ end
1177
+
1178
+ def sanitized_object_name
1179
+ @sanitized_object_name ||= @object_name.to_s.gsub(/\]\[|[^-a-zA-Z0-9:.]/, "_").sub(/_$/, "")
1180
+ end
1181
+
1182
+ def humanized_attribute_name(method)
1183
+ if @object && @object.class.respond_to?(:human_attribute_name)
1184
+ @object.class.human_attribute_name(method.to_s)
1185
+ else
1186
+ method.to_s.send(@@label_str_method)
1187
+ end
1188
+ end
1189
+
1190
+ def localized_attribute_string(attr_name, attr_value, i18n_key)
1191
+ if attr_value.is_a?(String)
1192
+ attr_value
1193
+ else
1194
+ use_i18n = attr_value.nil? ? @@i18n_lookups_by_default : attr_value
1195
+ if use_i18n
1196
+ model_name = @object.class.name.underscore
1197
+ action_name = template.params[:action].to_s rescue ''
1198
+ attribute_name = attr_name.to_s
1199
+
1200
+ defaults = I18N_SCOPES.collect do |i18n_scope|
1201
+ i18n_path = i18n_scope.dup
1202
+ i18n_path.gsub!('{{action}}', action_name)
1203
+ i18n_path.gsub!('{{model}}', model_name)
1204
+ i18n_path.gsub!('{{attribute}}', attribute_name)
1205
+ i18n_path.gsub!('..', '.')
1206
+ i18n_path.to_sym
1207
+ end
1208
+ defaults << ''
1209
+
1210
+ i18n_value = ::I18n.t(defaults.shift, :default => defaults,
1211
+ :scope => "formtastic.#{i18n_key.to_s.pluralize}")
1212
+ i18n_value.blank? ? nil : i18n_value
1213
+ end
1214
+ end
1215
+ end
1216
+
1217
+ end
1218
+
1219
+ # Wrappers around form_for (etc) with :builder => SemanticFormBuilder.
1220
+ #
1221
+ # * semantic_form_for(@post)
1222
+ # * semantic_fields_for(@post)
1223
+ # * semantic_form_remote_for(@post)
1224
+ # * semantic_remote_form_for(@post)
1225
+ #
1226
+ # Each of which are the equivalent of:
1227
+ #
1228
+ # * form_for(@post, :builder => Formtastic::SemanticFormBuilder))
1229
+ # * fields_for(@post, :builder => Formtastic::SemanticFormBuilder))
1230
+ # * form_remote_for(@post, :builder => Formtastic::SemanticFormBuilder))
1231
+ # * remote_form_for(@post, :builder => Formtastic::SemanticFormBuilder))
1232
+ #
1233
+ # Example Usage:
1234
+ #
1235
+ # <% semantic_form_for @post do |f| %>
1236
+ # <%= f.input :title %>
1237
+ # <%= f.input :body %>
1238
+ # <% end %>
1239
+ #
1240
+ # The above examples use a resource-oriented style of form_for() helper where only the @post
1241
+ # object is given as an argument, but the generic style is also supported if you really want it,
1242
+ # as is forms with inline objects (Post.new) rather than objects with instance variables (@post):
1243
+ #
1244
+ # <% semantic_form_for :post, @post, :url => posts_path do |f| %>
1245
+ # ...
1246
+ # <% end %>
1247
+ #
1248
+ # <% semantic_form_for :post, Post.new, :url => posts_path do |f| %>
1249
+ # ...
1250
+ # <% end %>
1251
+ #
1252
+ # The shorter, resource-oriented style is most definitely preferred, and has recieved the most
1253
+ # testing to date.
1254
+ #
1255
+ # Please note: Although it's possible to call Rails' built-in form_for() helper without an
1256
+ # object, all semantic forms *must* have an object (either Post.new or @post), as Formtastic
1257
+ # has too many dependencies on an ActiveRecord object being present.
1258
+ #
1259
+ module SemanticFormHelper
1260
+ @@builder = Formtastic::SemanticFormBuilder
1261
+
1262
+ # cattr_accessor :builder
1263
+ def self.builder=(val)
1264
+ @@builder = val
1265
+ end
1266
+
1267
+ [:form_for, :fields_for, :form_remote_for, :remote_form_for].each do |meth|
1268
+ src = <<-END_SRC
1269
+ def semantic_#{meth}(record_or_name_or_array, *args, &proc)
1270
+ options = args.extract_options!
1271
+ options[:builder] = @@builder
1272
+ options[:html] ||= {}
1273
+
1274
+ class_names = options[:html][:class] ? options[:html][:class].split(" ") : []
1275
+ class_names << "formtastic"
1276
+ class_names << case record_or_name_or_array
1277
+ when String, Symbol then record_or_name_or_array.to_s # :post => "post"
1278
+ when Array then record_or_name_or_array.last.class.to_s.underscore # [@post, @comment] # => "comment"
1279
+ else record_or_name_or_array.class.to_s.underscore # @post => "post"
1280
+ end
1281
+ options[:html][:class] = class_names.join(" ")
1282
+
1283
+ #{meth}(record_or_name_or_array, *(args << options), &proc)
1284
+ end
1285
+ END_SRC
1286
+ module_eval src, __FILE__, __LINE__
1287
+ end
1288
+ end
1289
+ end