jferris-formtastic 0.2.1.0.1246297983

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