justinfrench-formtastic 0.1.1
Sign up to get free protection for your applications and to get access to all the features.
- data/MIT-LICENSE +20 -0
- data/README.textile +324 -0
- data/Rakefile +58 -0
- data/lib/formtastic.rb +905 -0
- data/lib/justin_french/formtastic.rb +10 -0
- data/lib/locale/en.yml +13 -0
- data/rails/init.rb +3 -0
- data/spec/formtastic_spec.rb +2550 -0
- data/spec/test_helper.rb +14 -0
- metadata +64 -0
data/MIT-LICENSE
ADDED
@@ -0,0 +1,20 @@
|
|
1
|
+
Copyright (c) 2008 Justin French
|
2
|
+
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining
|
4
|
+
a copy of this software and associated documentation files (the
|
5
|
+
"Software"), to deal in the Software without restriction, including
|
6
|
+
without limitation the rights to use, copy, modify, merge, publish,
|
7
|
+
distribute, sublicense, and/or sell copies of the Software, and to
|
8
|
+
permit persons to whom the Software is furnished to do so, subject to
|
9
|
+
the following conditions:
|
10
|
+
|
11
|
+
The above copyright notice and this permission notice shall be
|
12
|
+
included in all copies or substantial portions of the Software.
|
13
|
+
|
14
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
15
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
16
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
17
|
+
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
18
|
+
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
19
|
+
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
20
|
+
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
data/README.textile
ADDED
@@ -0,0 +1,324 @@
|
|
1
|
+
h1. Formtastic 0.1.1
|
2
|
+
|
3
|
+
Formtastic is a Rails FormBuilder DSL (with some other goodies) to make it far easier to create beautiful, semantically rich, syntactically awesome, readily stylable and wonderfully accessible HTML forms in your Rails applications.
|
4
|
+
|
5
|
+
h2. The Story
|
6
|
+
|
7
|
+
One day, I finally had enough, so I opened up my text editor, and wrote a DSL for how I'd like to author forms:
|
8
|
+
|
9
|
+
<pre>
|
10
|
+
<% semantic_form_for @article do |form| %>
|
11
|
+
|
12
|
+
<% form.inputs :name => "Basic" do %>
|
13
|
+
<%= form.input :title %>
|
14
|
+
<%= form.input :body %>
|
15
|
+
<%= form.input :section %>
|
16
|
+
<%= form.input :publication_state, :as => :radio %>
|
17
|
+
<%= form.input :author %>
|
18
|
+
<%= form.input :allow_comments, :label => "Allow commenting on this article" %>
|
19
|
+
<% end %>
|
20
|
+
|
21
|
+
<% form.inputs :name => "Advanced" do %>
|
22
|
+
<%= form.input :keywords, :required => false, :hint => "Example: ruby, rails, forms" %>
|
23
|
+
<%= form.input :extract, :required => false %>
|
24
|
+
<%= form.input :description, :required => false %>
|
25
|
+
<%= form.input :url_title, :required => false %>
|
26
|
+
<% end %>
|
27
|
+
|
28
|
+
<% form.buttons do %>
|
29
|
+
<%= form.commit_button %>
|
30
|
+
<% end %>
|
31
|
+
|
32
|
+
<% end %>
|
33
|
+
</pre>
|
34
|
+
|
35
|
+
I also wrote the accompanying HTML output I expected, favoring something very similar to the fieldsets, lists and other semantic elements Aaron Gustafson presented in "Learning to Love Forms":http://www.slideshare.net/AaronGustafson/learning-to-love-forms-web-directions-south-07, hacking together enough Ruby to prove it could be done.
|
36
|
+
|
37
|
+
|
38
|
+
h2. It's better than _SomeOtherFormBuilder_ because...
|
39
|
+
|
40
|
+
* it can handle @belongs_to@ associations (like Post belongs_to :author), rendering a select or set of radio inputs with choices from the parent model
|
41
|
+
* it can handle @has_many@ and @has_and_belongs_to_many@ associations (like Post has_many :tags), rendering a multi-select with choices from the child models
|
42
|
+
* it's Rails 2.3-ready (including nested forms)
|
43
|
+
* it has internationalization (I18n)!
|
44
|
+
* it's _really_ quick to get started with a basic form in place (4 lines), then go back to add in more detail if you need it
|
45
|
+
* there's heaps of elements, id and class attributes for you to hook in your CSS and JS
|
46
|
+
* it handles real world stuff like inline hints, inline error messages & help text
|
47
|
+
* it doesn't hijack or change any of the standard Rails form inputs, so you can still use them as expected (even mix and match)
|
48
|
+
* it's got absolutely awesome spec coverage
|
49
|
+
* there's a bunch of people using and working on it (it's not just one developer building half a solution)
|
50
|
+
|
51
|
+
|
52
|
+
h2. Why?
|
53
|
+
|
54
|
+
* web apps = lots of forms
|
55
|
+
* forms are so friggin' boring to code
|
56
|
+
* semantically rich & accessible forms really are possible
|
57
|
+
* the "V" is way behind the "M" and "C" in Rails' MVC – it's the ugly sibling
|
58
|
+
* best practices and common patterns have to start somewhere
|
59
|
+
* i need a challenge
|
60
|
+
|
61
|
+
|
62
|
+
h2. Opinions
|
63
|
+
|
64
|
+
* it should be easier to do things the right way than the wrong way
|
65
|
+
* sometimes _more mark-up_ is better
|
66
|
+
* elements and attribute hooks are _gold_ for stylesheet authors
|
67
|
+
* make the common things we do easy, yet still ensure uncommon things are still possible
|
68
|
+
|
69
|
+
|
70
|
+
h2. Installation
|
71
|
+
|
72
|
+
You can (and should) get it as a gem:
|
73
|
+
|
74
|
+
<pre>
|
75
|
+
gem install justinfrench-formtastic
|
76
|
+
</pre>
|
77
|
+
|
78
|
+
And then add it as a dependency in your environment.rb file:
|
79
|
+
|
80
|
+
<pre>
|
81
|
+
config.gem "justinfrench-formtastic",
|
82
|
+
:lib => 'formtastic',
|
83
|
+
:source => 'http://gems.github.com',
|
84
|
+
:version => '0.1.1'
|
85
|
+
</pre>
|
86
|
+
|
87
|
+
If you're a little more old school, install it as a plugin:
|
88
|
+
|
89
|
+
<pre>
|
90
|
+
./script/install plugin git://github.com/justinfrench/formtastic.git
|
91
|
+
</pre>
|
92
|
+
|
93
|
+
|
94
|
+
h2. Usage
|
95
|
+
|
96
|
+
Forms are really boring to code... you want to get onto the good stuff as fast as possible.
|
97
|
+
|
98
|
+
This renders a set of inputs (one for _most_ columns in the database table, and one for each ActiveRecord belongs_to, has_many or has_and_belongs_to_many association) and a submit button:
|
99
|
+
|
100
|
+
<pre>
|
101
|
+
<% semantic_form_for @user do |form| %>
|
102
|
+
<%= form.inputs %>
|
103
|
+
<%= form.buttons %>
|
104
|
+
<% end %>
|
105
|
+
</pre>
|
106
|
+
|
107
|
+
If you want to specify the order of the fields, skip some of the fields or even add in fields that Formtastic couldn't detect, you can pass in a list of field names to @inputs@ and list of button names to @buttons@:
|
108
|
+
|
109
|
+
<pre>
|
110
|
+
<% semantic_form_for @user do |form| %>
|
111
|
+
<%= form.inputs :title, :body, :section, :categories, :created_at %>
|
112
|
+
<%= form.buttons :commit %>
|
113
|
+
<% end %>
|
114
|
+
</pre>
|
115
|
+
|
116
|
+
If you want control over the input type Formtastic uses for each field, you can expand the @inputs@ and @buttons@ blocks. This specifies the :section input should be a set of radio buttons (rather than the default select box), and that the :created_at field should be a string (rather than the default datetime selects):
|
117
|
+
|
118
|
+
<pre>
|
119
|
+
<% semantic_form_for @post do |form| %>
|
120
|
+
<% form.inputs do %>
|
121
|
+
<%= form.input :title %>
|
122
|
+
<%= form.input :body %>
|
123
|
+
<%= form.input :section, :as => :radio %>
|
124
|
+
<%= form.input :categories %>
|
125
|
+
<%= form.input :created_at, :as => :string %>
|
126
|
+
<% end %>
|
127
|
+
<% form.buttons do %>
|
128
|
+
<%= form.commit_button %>
|
129
|
+
<% end %>
|
130
|
+
<% end %>
|
131
|
+
</pre>
|
132
|
+
|
133
|
+
If you want to customize the label text, or render some hint text below the field, specify which fields are required/option, or break the form into two fieldsets, the DSL is pretty comprehensive:
|
134
|
+
|
135
|
+
<pre>
|
136
|
+
<% semantic_form_for @post do |form| %>
|
137
|
+
<% form.inputs :name => "Basic", :id => "basic" do %>
|
138
|
+
<%= form.input :title %>
|
139
|
+
<%= form.input :body %>
|
140
|
+
<% end %>
|
141
|
+
<% form.inputs :name => "Advanced Options", :id => "advanced" do %>
|
142
|
+
<%= form.input :slug, :label => "URL Title", :hint => "Created automatically if left blank", :required => false %>
|
143
|
+
<%= form.input :section, :as => :radio %>
|
144
|
+
<%= form.input :user, :label => "Author", :label_method => :full_name, %>
|
145
|
+
<%= form.input :categories, :required => false %>
|
146
|
+
<%= form.input :created_at, :as => :string, :label => "Publication Date", :required => false %>
|
147
|
+
<% end %>
|
148
|
+
<% form.buttons do %>
|
149
|
+
<%= form.commit_button %>
|
150
|
+
<% end %>
|
151
|
+
<% end %>
|
152
|
+
</pre>
|
153
|
+
|
154
|
+
Nested forms (Rails 2.3) are also supported:
|
155
|
+
|
156
|
+
<pre>
|
157
|
+
<% semantic_form_for @post do |post| %>
|
158
|
+
<%= post.semantic_fields_for :author do |author| %>
|
159
|
+
<%= author.inputs %>
|
160
|
+
<%= end %>
|
161
|
+
<%= post.buttons %>
|
162
|
+
<% end %>
|
163
|
+
</pre>
|
164
|
+
|
165
|
+
|
166
|
+
h2. The Available Inputs
|
167
|
+
|
168
|
+
* :select (a select menu) - default for ActiveRecord associations (belongs_to, has_many, has_and_belongs_to_many)
|
169
|
+
* :radio (a set of radio inputs) - alternative to :select for ActiveRecord belongs_to associations
|
170
|
+
* :password (a password input) - default for :string column types with 'password' in the method name
|
171
|
+
* :text (a textarea) - default for :text column types
|
172
|
+
* :date (a date select) - default for :date column types
|
173
|
+
* :datetime (a date and time select) - default for :datetime and :timestamp column types
|
174
|
+
* :time (a time select) - default for :time column types
|
175
|
+
* :boolean (a checkbox) - default for :boolean column types
|
176
|
+
* :boolean_select (a yes/no select box)
|
177
|
+
* :string (a text field) - default for :string column types
|
178
|
+
* :numeric (a text field, like string) - default for :integer, :float and :decimal column types
|
179
|
+
* :file (a file field) - default for paperclip or attachment_fu attributes
|
180
|
+
|
181
|
+
The documentation is pretty good for each of these (what it does, what the output is, what the options are, etc) so go check it out.
|
182
|
+
|
183
|
+
|
184
|
+
h2. Configuration
|
185
|
+
|
186
|
+
If you wish, put something like this in config/initializers/formtastic_config.rb:
|
187
|
+
|
188
|
+
<pre>
|
189
|
+
# Set the default text field size when input is a string. Default is 50
|
190
|
+
Formtastic::SemanticFormBuilder.default_text_field_size = 30
|
191
|
+
|
192
|
+
# Should all fields be considered "required" by default
|
193
|
+
# Defaults to true, see ValidationReflection notes below
|
194
|
+
Formtastic::SemanticFormBuilder.all_fields_required_by_default = false
|
195
|
+
|
196
|
+
# Set the string that will be appended to the labels/fieldsets which are required
|
197
|
+
# It accepts string or procs and the default is a localized version of
|
198
|
+
# '<abbr title="required">*</abbr>'. In other words, if you configure formtastic.required
|
199
|
+
# in your locale, it will replace the abbr title properly. But if you don't want to use
|
200
|
+
# abbr tag, you can simply give a string as below
|
201
|
+
Formtastic::SemanticFormBuilder.required_string = "(required)"
|
202
|
+
|
203
|
+
# Set the string that will be appended to the labels/fieldsets which are optional
|
204
|
+
# Defaults to an empty string ("") and also accepts procs (see required_string above)
|
205
|
+
Formtastic::SemanticFormBuilder.optional_string = "(optional)"
|
206
|
+
|
207
|
+
# Set the way inline errors will be displayed.
|
208
|
+
# Defaults to :sentence, valid options are :sentence, :list and :none
|
209
|
+
Formtastic::SemanticFormBuilder.inline_errors = :list
|
210
|
+
|
211
|
+
# Set the method to call on label text to transform or format it for human-friendly reading
|
212
|
+
# Defaults to :to_s, because we are already using human_attribute_name when creating labels,
|
213
|
+
# but you might want to change for :titleize or another string method
|
214
|
+
Formtastic::SemanticFormBuilder.label_str_method = :titleize
|
215
|
+
|
216
|
+
# Set the array of methods to try calling on parent objects in :select and :radio inputs
|
217
|
+
# for the text inside each @<option>@ tag or alongside each radio @<input>@. The first method
|
218
|
+
# that is found on the object will be used.
|
219
|
+
# Defaults to ["to_label", "display_name", "full_name", "name", "title", "username", "login", "value", "to_s"]
|
220
|
+
Formtastic::SemanticFormBuilder.collection_label_methods = ["title_and_author", "display_name", "login", "to_s"]
|
221
|
+
|
222
|
+
# Formtastic by default renders inside li tags the input, hints and then
|
223
|
+
# errors messages. Sometimes you want the hints to be rendered first than
|
224
|
+
# the input, in the following order: hints, input and errors. You can
|
225
|
+
# customize it doing just as below:
|
226
|
+
Formtastic::SemanticFormBuilder.inline_order = [:hints, :input, :errors]
|
227
|
+
</pre>
|
228
|
+
|
229
|
+
|
230
|
+
h2. Internationalization (I18n)
|
231
|
+
|
232
|
+
Supports I18n! ActiveRecord object names and attributes are, by default, taken from calling @object.human_name and @object.human_attribute_name(attr) respectively. There are a few words specific to Formtastic that can be translated.
|
233
|
+
|
234
|
+
Here is an example locale file:
|
235
|
+
|
236
|
+
<pre>
|
237
|
+
en:
|
238
|
+
formtastic:
|
239
|
+
yes: 'Yes'
|
240
|
+
no: 'No'
|
241
|
+
create: 'Create'
|
242
|
+
save: 'Save'
|
243
|
+
year: 'Year'
|
244
|
+
month: 'Month'
|
245
|
+
day: 'Day'
|
246
|
+
hour: 'Hour'
|
247
|
+
minute: 'Minute'
|
248
|
+
second: 'Second'
|
249
|
+
required: 'required'
|
250
|
+
</pre>
|
251
|
+
|
252
|
+
|
253
|
+
h2. ValidationReflection plugin
|
254
|
+
|
255
|
+
If you have the "ValidationReflection":http://github.com/redinger/validation_reflection plugin installed, you won't have to specify the :required option (it checks the validations on the model instead).
|
256
|
+
|
257
|
+
|
258
|
+
h2. Status
|
259
|
+
|
260
|
+
*THINGS ARE GOING TO CHANGE A BIT BEFORE WE HIT 1.0.*
|
261
|
+
|
262
|
+
It's a work in progress and a bit rough around the edges still, but I hope you try it and offer some suggestions and improvements anyway.
|
263
|
+
|
264
|
+
On the plus side, it has a comprehensive spec suite and contributions from at least ten independent developers.
|
265
|
+
|
266
|
+
"Wishlist":http://wiki.github.com/justinfrench/formtastic/wishlist on the wiki is serving as pretty good documentation for the roadmap to 1.0 and beyond right now, but I'll work on getting a real tracking system or something happening soon.
|
267
|
+
|
268
|
+
|
269
|
+
h2. Dependencies
|
270
|
+
|
271
|
+
There are none, but...
|
272
|
+
|
273
|
+
* if you have the "ValidationReflection":http://github.com/redinger/validation_reflection plugin is installed, you won't have to specify the :required option (it checks the validations on the model instead)
|
274
|
+
* rspec, rspec_hpricot_matchers and rcov gems (plus any of their own dependencies) are required for the test suite
|
275
|
+
|
276
|
+
|
277
|
+
h2. Compatibility
|
278
|
+
|
279
|
+
I'm only testing Formtastic with the latest Rails 2.2.x stable release, and it should be fine under Rails 2.3 as well (including nested forms). Patches are welcome to allow backwards compatibility, but I don't have the energy!
|
280
|
+
|
281
|
+
|
282
|
+
|
283
|
+
h2. What about Stylesheets?
|
284
|
+
|
285
|
+
A proof-of-concept (very much a work-in-progress) stylesheet is provided which you can include in your layout. Customization is best achieved by overriding these styles in an additional stylesheet so that the Formtastic styles can be updated without clobbering your changes.
|
286
|
+
|
287
|
+
1. Use the generator to copy the formtastic.css and formtastic_changes.css into your public directory
|
288
|
+
|
289
|
+
<pre>
|
290
|
+
./script/generate formtastic_stylesheets
|
291
|
+
</pre>
|
292
|
+
|
293
|
+
2. Add both formtastic.css and formtastic_changes.css to your layout:
|
294
|
+
|
295
|
+
<pre>
|
296
|
+
<%= stylesheet_link_tag "formtastic" %>
|
297
|
+
<%= stylesheet_link_tag "formtastic_changes" %>
|
298
|
+
</pre>
|
299
|
+
|
300
|
+
|
301
|
+
h2. Many thanks to Formtastic's contributors
|
302
|
+
|
303
|
+
* "Justin French":http://justinfrench.com
|
304
|
+
* "Xavier Shay":http://rhnh.net
|
305
|
+
* "Bin Dong":http://github.com/dongbin
|
306
|
+
* "Ben Hamill":http://blog.benhamill.com/
|
307
|
+
* "Pat Allan":http://github.com/freelancing-god
|
308
|
+
* "negonicrac":http://github.com/negonicrac
|
309
|
+
* "Andy Pearson":http://github.com/andypearson
|
310
|
+
* "Mark Mansour":http://stateofflux.com
|
311
|
+
* "Tien Dung":http://github.com/tiendung
|
312
|
+
* "Sascha Hoellger":http://github.com/mitnal
|
313
|
+
* "Jeff Smick":http://github.com/sprsquish
|
314
|
+
* "José Valim":http://github.com/josevalim
|
315
|
+
|
316
|
+
|
317
|
+
h2. Project Info
|
318
|
+
|
319
|
+
Formtastic is hosted on Github: http://github.com/justinfrench/formtastic/, where your contributions, forkings, comments and feedback are greatly welcomed.
|
320
|
+
|
321
|
+
There's also a newly created "Formtastic Google Group":http://groups.google.com.au/group/formtastic.
|
322
|
+
|
323
|
+
|
324
|
+
Copyright (c) 2007-2008 Justin French, released under the MIT license.
|
data/Rakefile
ADDED
@@ -0,0 +1,58 @@
|
|
1
|
+
require 'rake'
|
2
|
+
require 'rake/rdoctask'
|
3
|
+
require 'spec/rake/spectask'
|
4
|
+
|
5
|
+
begin
|
6
|
+
GEM = "formtastic"
|
7
|
+
AUTHOR = "Justin French"
|
8
|
+
EMAIL = "justin@indent.com.au"
|
9
|
+
SUMMARY = "A Rails form builder plugin/gem with semantically rich and accessible markup"
|
10
|
+
HOMEPAGE = "http://github.com/justinfrench/formtastic/tree/master"
|
11
|
+
|
12
|
+
require 'jeweler'
|
13
|
+
Jeweler::Tasks.new do |s|
|
14
|
+
s.name = GEM
|
15
|
+
s.summary = SUMMARY
|
16
|
+
s.email = EMAIL
|
17
|
+
s.homepage = HOMEPAGE
|
18
|
+
s.description = SUMMARY
|
19
|
+
s.author = AUTHOR
|
20
|
+
|
21
|
+
s.require_path = 'lib'
|
22
|
+
s.autorequire = GEM
|
23
|
+
s.files = %w(MIT-LICENSE README.textile Rakefile) + Dir.glob("{rails,lib,spec}/**/*")
|
24
|
+
end
|
25
|
+
rescue LoadError
|
26
|
+
puts "Jeweler, or one of its dependencies, is not available. Install it with: sudo gem install technicalpickles-jeweler -s http://gems.github.com"
|
27
|
+
end
|
28
|
+
|
29
|
+
desc 'Default: run unit specs.'
|
30
|
+
task :default => :spec
|
31
|
+
|
32
|
+
desc 'Test the formtastic plugin.'
|
33
|
+
Spec::Rake::SpecTask.new('spec') do |t|
|
34
|
+
t.spec_files = FileList['spec/**/*_spec.rb']
|
35
|
+
t.spec_opts = ["-c"]
|
36
|
+
end
|
37
|
+
|
38
|
+
desc 'Test the formtastic plugin with specdoc formatting and colors'
|
39
|
+
Spec::Rake::SpecTask.new('specdoc') do |t|
|
40
|
+
t.spec_files = FileList['spec/**/*_spec.rb']
|
41
|
+
t.spec_opts = ["--format specdoc", "-c"]
|
42
|
+
end
|
43
|
+
|
44
|
+
desc 'Generate documentation for the formtastic plugin.'
|
45
|
+
Rake::RDocTask.new(:rdoc) do |rdoc|
|
46
|
+
rdoc.rdoc_dir = 'rdoc'
|
47
|
+
rdoc.title = 'Formtastic'
|
48
|
+
rdoc.options << '--line-numbers' << '--inline-source'
|
49
|
+
rdoc.rdoc_files.include('README.textile')
|
50
|
+
rdoc.rdoc_files.include('lib/**/*.rb')
|
51
|
+
end
|
52
|
+
|
53
|
+
desc "Run all examples with RCov"
|
54
|
+
Spec::Rake::SpecTask.new('examples_with_rcov') do |t|
|
55
|
+
t.spec_files = FileList['spec/**/*_spec.rb']
|
56
|
+
t.rcov = true
|
57
|
+
t.rcov_opts = ['--exclude', 'spec,Library']
|
58
|
+
end
|
data/lib/formtastic.rb
ADDED
@@ -0,0 +1,905 @@
|
|
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 = :to_s
|
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
|
+
|
21
|
+
cattr_accessor :default_text_field_size, :all_fields_required_by_default, :required_string, :optional_string, :inline_errors, :label_str_method, :collection_label_methods, :inline_order
|
22
|
+
|
23
|
+
attr_accessor :template
|
24
|
+
|
25
|
+
|
26
|
+
# Returns a suitable form input for the given +method+, using the database column information
|
27
|
+
# and other factors (like the method name) to figure out what you probably want.
|
28
|
+
#
|
29
|
+
# Options:
|
30
|
+
#
|
31
|
+
# * :as - override the input type (eg force a :string to render as a :password field)
|
32
|
+
# * :label - use something other than the method name as the label (or fieldset legend) text
|
33
|
+
# * :required - specify if the column is required (true) or not (false)
|
34
|
+
# * :hint - provide some text to hint or help the user provide the correct information for a field
|
35
|
+
#
|
36
|
+
# Input Types:
|
37
|
+
#
|
38
|
+
# Most inputs map directly to one of ActiveRecord's column types by default (eg string_input),
|
39
|
+
# but there are a few special cases and some simplification (:integer, :float and :decimal
|
40
|
+
# columns all map to a single numeric_input, for example).
|
41
|
+
#
|
42
|
+
# * :select (a select menu for belongs_to associations) - default for columns ending in '_id'
|
43
|
+
# * :radio (a set of radio inputs for belongs_to associations) - alternative for columns ending in '_id'
|
44
|
+
# * :password (a password input) - default for :string column types with 'password' in the method name
|
45
|
+
# * :text (a textarea) - default for :text column types
|
46
|
+
# * :date (a date select) - default for :date column types
|
47
|
+
# * :datetime (a date and time select) - default for :datetime and :timestamp column types
|
48
|
+
# * :time (a time select) - default for :time column types
|
49
|
+
# * :boolean (a checkbox) - default for :boolean column types
|
50
|
+
# * :boolean_select (a yes/no select box)
|
51
|
+
# * :string (a text field) - default for :string column types
|
52
|
+
# * :numeric (a text field, like string) - default for :integer, :float and :decimal column types
|
53
|
+
#
|
54
|
+
# Example:
|
55
|
+
#
|
56
|
+
# <% semantic_form_for @employee do |form| %>
|
57
|
+
# <% form.inputs do -%>
|
58
|
+
# <%= form.input :name, :label => "Full Name"%>
|
59
|
+
# <%= form.input :manager_id, :as => :radio %>
|
60
|
+
# <%= form.input :hired_at, :as => :date, :label => "Date Hired" %>
|
61
|
+
# <%= form.input :phone, :required => false, :hint => "Eg: +1 555 1234" %>
|
62
|
+
# <% end %>
|
63
|
+
# <% end %>
|
64
|
+
def input(method, options = {})
|
65
|
+
raise NoMethodError.new("NoMethodError: form object does not respond to \"#{method}\"") unless @object.respond_to?(method)
|
66
|
+
|
67
|
+
|
68
|
+
options[:required] = method_required?(method, options[:required])
|
69
|
+
options[:label] ||= @object.class.human_attribute_name(method.to_s).send(@@label_str_method)
|
70
|
+
options[:as] ||= default_input_type(@object, method)
|
71
|
+
input_method = "#{options[:as]}_input"
|
72
|
+
|
73
|
+
html_class = [
|
74
|
+
options[:as].to_s,
|
75
|
+
(options[:required] ? 'required' : 'optional'),
|
76
|
+
(@object.errors.on(method.to_s) ? 'error' : nil)
|
77
|
+
].compact.join(" ")
|
78
|
+
|
79
|
+
html_id = generate_html_id(method)
|
80
|
+
|
81
|
+
list_item_content = @@inline_order.map do |type|
|
82
|
+
if type == :input
|
83
|
+
send(input_method, method, options)
|
84
|
+
else
|
85
|
+
send(:"inline_#{type}", method, options)
|
86
|
+
end
|
87
|
+
end.compact.join("\n")
|
88
|
+
|
89
|
+
return template.content_tag(:li, list_item_content, { :id => html_id, :class => html_class })
|
90
|
+
end
|
91
|
+
|
92
|
+
# Creates an input fieldset and ol tag wrapping for use around a set of inputs. It can be
|
93
|
+
# called either with a block (in which you can do the usual Rails form stuff, HTML, ERB, etc),
|
94
|
+
# or with a list of fields. These two examples are functionally equivalent:
|
95
|
+
#
|
96
|
+
# # With a block:
|
97
|
+
# <% semantic_form_for @post do |form| %>
|
98
|
+
# <% form.inputs do %>
|
99
|
+
# <%= form.input :title %>
|
100
|
+
# <%= form.input :body %>
|
101
|
+
# <% end %>
|
102
|
+
# <% end %>
|
103
|
+
#
|
104
|
+
# # With a list of fields:
|
105
|
+
# <% semantic_form_for @post do |form| %>
|
106
|
+
# <%= form.inputs :title, :body %>
|
107
|
+
# <% end %>
|
108
|
+
#
|
109
|
+
# # Output:
|
110
|
+
# <form ...>
|
111
|
+
# <fieldset class="inputs">
|
112
|
+
# <ol>
|
113
|
+
# <li class="string">...</li>
|
114
|
+
# <li class="text">...</li>
|
115
|
+
# </ol>
|
116
|
+
# </fieldset>
|
117
|
+
# </form>
|
118
|
+
#
|
119
|
+
# === Quick Forms
|
120
|
+
#
|
121
|
+
# When called without a block or a field list, an input is rendered for each column in the
|
122
|
+
# model's database table, just like Rails' scaffolding. You'll obviously want more control
|
123
|
+
# than this in a production application, but it's a great way to get started, then come back
|
124
|
+
# later to customise the form with a field list or a block of inputs. Example:
|
125
|
+
#
|
126
|
+
# <% semantic_form_for @post do |form| %>
|
127
|
+
# <%= form.inputs %>
|
128
|
+
# <% end %>
|
129
|
+
#
|
130
|
+
# === Options
|
131
|
+
#
|
132
|
+
# All options (with the exception of :name) are passed down to the fieldset as HTML
|
133
|
+
# attributes (id, class, style, etc). If provided, the :name option is passed into a
|
134
|
+
# legend tag inside the fieldset (otherwise a legend is not generated).
|
135
|
+
#
|
136
|
+
# # With a block:
|
137
|
+
# <% semantic_form_for @post do |form| %>
|
138
|
+
# <% form.inputs :name => "Create a new post", :style => "border:1px;" do %>
|
139
|
+
# ...
|
140
|
+
# <% end %>
|
141
|
+
# <% end %>
|
142
|
+
#
|
143
|
+
# # With a list (the options must come after the field list):
|
144
|
+
# <% semantic_form_for @post do |form| %>
|
145
|
+
# <%= form.inputs :title, :body, :name => "Create a new post", :style => "border:1px;" %>
|
146
|
+
# <% end %>
|
147
|
+
#
|
148
|
+
# === It's basically a fieldset!
|
149
|
+
#
|
150
|
+
# Instead of hard-coding fieldsets & legends into your form to logically group related fields,
|
151
|
+
# use inputs:
|
152
|
+
#
|
153
|
+
# <% semantic_form_for @post do |f| %>
|
154
|
+
# <% f.inputs do %>
|
155
|
+
# <%= f.input :title %>
|
156
|
+
# <%= f.input :body %>
|
157
|
+
# <% end %>
|
158
|
+
# <% f.inputs :name => "Advanced", :id => "advanced" do %>
|
159
|
+
# <%= f.input :created_at %>
|
160
|
+
# <%= f.input :user_id, :label => "Author" %>
|
161
|
+
# <% end %>
|
162
|
+
# <% end %>
|
163
|
+
#
|
164
|
+
# # Output:
|
165
|
+
# <form ...>
|
166
|
+
# <fieldset class="inputs">
|
167
|
+
# <ol>
|
168
|
+
# <li class="string">...</li>
|
169
|
+
# <li class="text">...</li>
|
170
|
+
# </ol>
|
171
|
+
# </fieldset>
|
172
|
+
# <fieldset class="inputs" id="advanced">
|
173
|
+
# <legend><span>Advanced</span></legend>
|
174
|
+
# <ol>
|
175
|
+
# <li class="datetime">...</li>
|
176
|
+
# <li class="select">...</li>
|
177
|
+
# </ol>
|
178
|
+
# </fieldset>
|
179
|
+
# </form>
|
180
|
+
def inputs(*args, &block)
|
181
|
+
html_options = args.extract_options!
|
182
|
+
html_options[:class] ||= "inputs"
|
183
|
+
|
184
|
+
if block_given?
|
185
|
+
field_set_and_list_wrapping(html_options, &block)
|
186
|
+
else
|
187
|
+
if args.empty?
|
188
|
+
args = @object.class.reflections.map { |n,_| n }
|
189
|
+
args += @object.class.content_columns.map(&:name)
|
190
|
+
end
|
191
|
+
contents = args.map { |method| input(method.to_sym) }
|
192
|
+
field_set_and_list_wrapping(html_options, contents)
|
193
|
+
end
|
194
|
+
end
|
195
|
+
alias_method :input_field_set, :inputs
|
196
|
+
|
197
|
+
# Creates a fieldset and ol tag wrapping for form buttons / actions as list items.
|
198
|
+
# See inputs documentation for a full example. The fieldset's default class attriute
|
199
|
+
# is set to "buttons".
|
200
|
+
#
|
201
|
+
# See inputs for html attributes and special options.
|
202
|
+
def buttons(*args, &block)
|
203
|
+
html_options = args.extract_options!
|
204
|
+
html_options[:class] ||= "buttons"
|
205
|
+
|
206
|
+
if block_given?
|
207
|
+
field_set_and_list_wrapping(html_options, &block)
|
208
|
+
else
|
209
|
+
args = [:commit] if args.empty?
|
210
|
+
contents = args.map { |button_name| send(:"#{button_name}_button") }
|
211
|
+
field_set_and_list_wrapping(html_options, contents)
|
212
|
+
end
|
213
|
+
end
|
214
|
+
alias_method :button_field_set, :buttons
|
215
|
+
|
216
|
+
# Creates a submit input tag with the value "Save [model name]" (for existing records) or
|
217
|
+
# "Create [model name]" (for new records) by default:
|
218
|
+
#
|
219
|
+
# <%= form.commit_button %> => <input name="commit" type="submit" value="Save Post" />
|
220
|
+
#
|
221
|
+
# The value of the button text can be overridden:
|
222
|
+
#
|
223
|
+
# <%= form.commit_button "Go" %> => <input name="commit" type="submit" value="Go" />
|
224
|
+
def commit_button(value = save_or_create_commit_button_text, options = {})
|
225
|
+
template.content_tag(:li, template.submit_tag(value), :class => "commit")
|
226
|
+
end
|
227
|
+
|
228
|
+
|
229
|
+
# A thin wrapper around #fields_for to set :builder => Formtastic::SemanticFormBuilder
|
230
|
+
# for nesting forms:
|
231
|
+
#
|
232
|
+
# # Example:
|
233
|
+
# <% semantic_form_for @post do |post| %>
|
234
|
+
# <% post.semantic_fields_for :author do |author| %>
|
235
|
+
# <% author.inputs :name %>
|
236
|
+
# <% end %>
|
237
|
+
# <% end %>
|
238
|
+
#
|
239
|
+
# # Output:
|
240
|
+
# <form ...>
|
241
|
+
# <fieldset class="inputs">
|
242
|
+
# <ol>
|
243
|
+
# <li class="string"><input type='text' name='post[author][name]' id='post_author_name' /></li>
|
244
|
+
# </ol>
|
245
|
+
# </fieldset>
|
246
|
+
# </form>
|
247
|
+
def semantic_fields_for(record_or_name_or_array, *args, &block)
|
248
|
+
opts = args.extract_options!
|
249
|
+
opts.merge!(:builder => Formtastic::SemanticFormBuilder)
|
250
|
+
args.push(opts)
|
251
|
+
fields_for(record_or_name_or_array, *args, &block)
|
252
|
+
end
|
253
|
+
|
254
|
+
protected
|
255
|
+
|
256
|
+
# Ensure :object => @object is set before sending the options down to the Rails layer.
|
257
|
+
# Also remove any Formtastic-specific options
|
258
|
+
def set_options(options)
|
259
|
+
opts = options.dup
|
260
|
+
[:value_method, :label_method, :collection, :required, :label, :as, :hint].each do |key|
|
261
|
+
opts.delete(key)
|
262
|
+
end
|
263
|
+
opts.merge(:object => @object)
|
264
|
+
end
|
265
|
+
|
266
|
+
def save_or_create_commit_button_text #:nodoc:
|
267
|
+
prefix = @object.new_record? ? 'create' : 'save'
|
268
|
+
[ I18n.t(prefix, :default => prefix, :scope => [:formtastic]),
|
269
|
+
@object.class.human_name
|
270
|
+
].join(' ').send(@@label_str_method)
|
271
|
+
end
|
272
|
+
|
273
|
+
# Determins if the attribute (eg :title) should be considered required or not.
|
274
|
+
#
|
275
|
+
# * if the :required option was provided in the options hash, the true/false value will be
|
276
|
+
# returned immediately, allowing the view to override any guesswork that follows:
|
277
|
+
# * if the :required option isn't provided in the options hash, and the ValidationReflection
|
278
|
+
# plugin is installed (http://github.com/redinger/validation_reflection), true is returned
|
279
|
+
# if the validates_presence_of macro has been used in the class for this attribute, or false
|
280
|
+
# otherwise.
|
281
|
+
# * if the :required option isn't provided, and the plugin isn't available, the value of the
|
282
|
+
# configuration option @@all_fields_required_by_default is used.
|
283
|
+
def method_required?(attribute, required_option) #:nodoc:
|
284
|
+
return required_option unless required_option.nil?
|
285
|
+
|
286
|
+
if @object.class.respond_to?(:reflect_on_all_validations)
|
287
|
+
attribute_sym = attribute.to_s.sub(/_id$/, '').to_sym
|
288
|
+
@object.class.reflect_on_all_validations.any? do |validation|
|
289
|
+
validation.macro == :validates_presence_of && validation.name == attribute_sym
|
290
|
+
end
|
291
|
+
else
|
292
|
+
@@all_fields_required_by_default
|
293
|
+
end
|
294
|
+
end
|
295
|
+
|
296
|
+
# Outputs a label and a select box containing options from the parent
|
297
|
+
# (belongs_to, has_many, has_and_belongs_to_many) association. If an association
|
298
|
+
# is has_many or has_and_belongs_to_many the select box will be set as multi-select
|
299
|
+
# and size = 5
|
300
|
+
#
|
301
|
+
# Example (belongs_to):
|
302
|
+
#
|
303
|
+
# f.input :author
|
304
|
+
#
|
305
|
+
# <label for="book_author_id">Author</label>
|
306
|
+
# <select id="book_author_id" name="book[author_id]">
|
307
|
+
# <option value="1">Justin French</option>
|
308
|
+
# <option value="2">Jane Doe</option>
|
309
|
+
# </select>
|
310
|
+
#
|
311
|
+
# Example (has_many):
|
312
|
+
#
|
313
|
+
# f.input :chapters
|
314
|
+
#
|
315
|
+
# <label for="book_chapter_ids">Chapters</label>
|
316
|
+
# <select id="book_chapter_ids" name="book[chapter_ids]">
|
317
|
+
# <option value="1">Chapter 1</option>
|
318
|
+
# <option value="2">Chapter 2</option>
|
319
|
+
# </select>
|
320
|
+
#
|
321
|
+
# Example (has_and_belongs_to_many):
|
322
|
+
#
|
323
|
+
# f.input :authors
|
324
|
+
#
|
325
|
+
# <label for="book_author_ids">Authors</label>
|
326
|
+
# <select id="book_author_ids" name="book[author_ids]">
|
327
|
+
# <option value="1">Justin French</option>
|
328
|
+
# <option value="2">Jane Doe</option>
|
329
|
+
# </select>
|
330
|
+
#
|
331
|
+
#
|
332
|
+
# You can customize the options available in the select by passing in a collection (Array) of
|
333
|
+
# ActiveRecord objects through the :collection option. If not provided, the choices are found
|
334
|
+
# by inferring the parent's class name from the method name and simply calling find(:all) on
|
335
|
+
# it (VehicleOwner.find(:all) in the example above).
|
336
|
+
#
|
337
|
+
# Examples:
|
338
|
+
#
|
339
|
+
# f.input :author, :collection => @authors
|
340
|
+
# f.input :author, :collection => Author.find(:all)
|
341
|
+
# f.input :author, :collection => [@justin, @kate]
|
342
|
+
# f.input :author, :collection => {@justin.name => @justin.id, @kate.name => @kate.id}
|
343
|
+
#
|
344
|
+
# Note: This input looks for a label method in the parent association.
|
345
|
+
#
|
346
|
+
# You can customize the text label inside each option tag, by naming the correct method
|
347
|
+
# (:full_name, :display_name, :account_number, etc) to call on each object in the collection
|
348
|
+
# by passing in the :label_method option. By default the :label_method is whichever element of
|
349
|
+
# Formtastic::SemanticFormBuilder.collection_label_methods is found first.
|
350
|
+
#
|
351
|
+
# Examples:
|
352
|
+
#
|
353
|
+
# f.input :author, :label_method => :full_name
|
354
|
+
# f.input :author, :label_method => :display_name
|
355
|
+
# f.input :author, :label_method => :to_s
|
356
|
+
# f.input :author, :label_method => :label
|
357
|
+
#
|
358
|
+
# You can also customize the value inside each option tag, by passing in the :value_method option.
|
359
|
+
# Usage is the same as the :label_method option
|
360
|
+
#
|
361
|
+
# Examples:
|
362
|
+
#
|
363
|
+
# f.input :author, :value_method => :full_name
|
364
|
+
# f.input :author, :value_method => :display_name
|
365
|
+
# f.input :author, :value_method => :to_s
|
366
|
+
# f.input :author, :value_method => :value
|
367
|
+
#
|
368
|
+
# You can pass html_options to the select tag using :input_html => {}
|
369
|
+
#
|
370
|
+
# Examples:
|
371
|
+
#
|
372
|
+
# f.input :authors, :html => {:size => 20, :multiple => true}
|
373
|
+
def select_input(method, options)
|
374
|
+
options[:collection] ||= find_parent_objects_for_column(method)
|
375
|
+
options[:label_method] ||= detect_label_method(options[:collection])
|
376
|
+
options[:value_method] ||= :id
|
377
|
+
options[:input_html] ||= {}
|
378
|
+
|
379
|
+
if (reflection = find_reflection(method)) && reflection.macro != :belongs_to
|
380
|
+
options[:input_html][:multiple] ||= true
|
381
|
+
options[:input_html][:size] ||= 5
|
382
|
+
end
|
383
|
+
|
384
|
+
input_name = generate_association_input_name(method)
|
385
|
+
html_options = options.delete(:input_html)
|
386
|
+
choices = formatted_collection(options[:collection], options[:label_method], options[:value_method])
|
387
|
+
input_label(input_name, options) + template.select(@object_name, input_name, choices, set_options(options), html_options)
|
388
|
+
end
|
389
|
+
|
390
|
+
def detect_label_method(collection) #:nodoc:
|
391
|
+
(!collection.instance_of?(Hash)) ? @@collection_label_methods.detect { |m| collection.first.respond_to?(m) } : nil
|
392
|
+
end
|
393
|
+
|
394
|
+
def formatted_collection(collection, label_method, value_method = :id) #:nodoc:
|
395
|
+
return collection if (collection.instance_of?(Hash) || (collection.instance_of?(Array) && collection.first.instance_of?(String)))
|
396
|
+
collection.map { |o| [o.send(label_method), o.send(value_method)] }
|
397
|
+
end
|
398
|
+
|
399
|
+
# Outputs a fieldset containing a legend for the label text, and an ordered list (ol) of list
|
400
|
+
# items, one for each possible choice in the belongs_to association. Each li contains a
|
401
|
+
# label and a radio input.
|
402
|
+
#
|
403
|
+
# Example:
|
404
|
+
#
|
405
|
+
# f.input :author, :as => :radio
|
406
|
+
#
|
407
|
+
# Output:
|
408
|
+
#
|
409
|
+
# <fieldset>
|
410
|
+
# <legend><span>Author</span></legend>
|
411
|
+
# <ol>
|
412
|
+
# <li>
|
413
|
+
# <label for="book_author_id_1"><input id="book_author_id_1" name="book[author_id]" type="radio" value="1" /> Justin French</label>
|
414
|
+
# </li>
|
415
|
+
# <li>
|
416
|
+
# <label for="book_author_id_2"><input id="book_author_id_2" name="book[owner_id]" type="radio" value="2" /> Kate French</label>
|
417
|
+
# </li>
|
418
|
+
# </ol>
|
419
|
+
# </fieldset>
|
420
|
+
#
|
421
|
+
# You can customize the options available in the set by passing in a collection (Array) of
|
422
|
+
# ActiveRecord objects through the :collection option. If not provided, the choices are found
|
423
|
+
# by inferring the parent's class name from the method name and simply calling find(:all) on
|
424
|
+
# it (VehicleOwner.find(:all) in the example above).
|
425
|
+
#
|
426
|
+
# Examples:
|
427
|
+
#
|
428
|
+
# f.input :author, :as => :radio, :collection => @authors
|
429
|
+
# f.input :author, :as => :radio, :collection => Author.find(:all)
|
430
|
+
# f.input :author, :as => :radio, :collection => [@justin, @kate]
|
431
|
+
#
|
432
|
+
# You can also customize the text label inside each option tag, by naming the correct method
|
433
|
+
# (:full_name, :display_name, :account_number, etc) to call on each object in the collection
|
434
|
+
# by passing in the :label_method option. By default the :label_method is whichever element of
|
435
|
+
# Formtastic::SemanticFormBuilder.collection_label_methods is found first.
|
436
|
+
#
|
437
|
+
# Examples:
|
438
|
+
#
|
439
|
+
# f.input :author, :as => :radio, :label_method => :full_name
|
440
|
+
# f.input :author, :as => :radio, :label_method => :display_name
|
441
|
+
# f.input :author, :as => :radio, :label_method => :to_s
|
442
|
+
# f.input :author, :as => :radio, :label_method => :label
|
443
|
+
#
|
444
|
+
# Finally, you can set :value_as_class => true if you want that LI wrappers
|
445
|
+
# contains a class with the wrapped radio input value. This is used by
|
446
|
+
# <tt>boolean_radio_input</tt> and you can see an example there.
|
447
|
+
#
|
448
|
+
def radio_input(method, options)
|
449
|
+
options[:collection] ||= find_parent_objects_for_column(method)
|
450
|
+
options[:label_method] ||= detect_label_method(options[:collection])
|
451
|
+
|
452
|
+
input_name = generate_association_input_name(method)
|
453
|
+
value_as_class = options.delete(:value_as_class)
|
454
|
+
|
455
|
+
choices = formatted_collection(options[:collection], options[:label_method])
|
456
|
+
template.content_tag(:fieldset,
|
457
|
+
%{<legend><span>#{label_text(method, options)}</span></legend>} +
|
458
|
+
template.content_tag(:ol,
|
459
|
+
choices.map { |c|
|
460
|
+
label = (!c.instance_of?(String)) ? c.first : c
|
461
|
+
value = (!c.instance_of?(String)) ? c.last : c
|
462
|
+
|
463
|
+
li_content = template.content_tag(:label,
|
464
|
+
"#{template.radio_button(@object_name, input_name, value, set_options(options))} #{label}",
|
465
|
+
:for => generate_html_id(input_name, value.to_s.downcase)
|
466
|
+
)
|
467
|
+
|
468
|
+
li_options = value_as_class ? { :class => value.to_s.downcase } : {}
|
469
|
+
template.content_tag(:li, li_content, li_options)
|
470
|
+
}
|
471
|
+
)
|
472
|
+
)
|
473
|
+
end
|
474
|
+
|
475
|
+
# Outputs a label and a password input, nothing fancy.
|
476
|
+
def password_input(method, options)
|
477
|
+
input_label(method, options) +
|
478
|
+
template.password_field(@object_name, method, default_string_options(method))
|
479
|
+
end
|
480
|
+
|
481
|
+
|
482
|
+
# Outputs a label and a textarea, nothing fancy.
|
483
|
+
def text_input(method, options)
|
484
|
+
input_label(method, options) + template.text_area(@object_name, method, set_options(options))
|
485
|
+
end
|
486
|
+
|
487
|
+
|
488
|
+
# Outputs a label and a text input, nothing fancy, but it does pick up some attributes like
|
489
|
+
# size and maxlength -- see default_string_options() for the low-down.
|
490
|
+
def string_input(method, options)
|
491
|
+
input_label(method, options) +
|
492
|
+
template.text_field(@object_name, method, default_string_options(method))
|
493
|
+
end
|
494
|
+
|
495
|
+
|
496
|
+
# Same as string_input for now
|
497
|
+
def numeric_input(method, options)
|
498
|
+
input_label(method, options) +
|
499
|
+
template.text_field(@object_name, method, default_string_options(method))
|
500
|
+
end
|
501
|
+
|
502
|
+
# Outputs label and file field
|
503
|
+
def file_input(method, options)
|
504
|
+
input_label(method, options) +
|
505
|
+
template.file_field(@object_name, method, set_options(options))
|
506
|
+
end
|
507
|
+
|
508
|
+
|
509
|
+
# Outputs a fieldset with a legend for the method label, and a ordered list (ol) of list
|
510
|
+
# items (li), one for each fragment for the date (year, month, day). Each li contains a label
|
511
|
+
# (eg "Year") and a select box. See date_or_datetime_input for a more detailed output example.
|
512
|
+
#
|
513
|
+
# Some of Rails' options for select_date are supported, but not everything yet.
|
514
|
+
def date_input(method, options)
|
515
|
+
date_or_datetime_input(method, options.merge(:discard_hour => true))
|
516
|
+
end
|
517
|
+
|
518
|
+
|
519
|
+
# Outputs a fieldset with a legend for the method label, and a ordered list (ol) of list
|
520
|
+
# items (li), one for each fragment for the date (year, month, day, hour, min, sec). Each li
|
521
|
+
# contains a label (eg "Year") and a select box. See date_or_datetime_input for a more
|
522
|
+
# detailed output example.
|
523
|
+
#
|
524
|
+
# Some of Rails' options for select_date are supported, but not everything yet.
|
525
|
+
def datetime_input(method, options)
|
526
|
+
date_or_datetime_input(method, options)
|
527
|
+
end
|
528
|
+
|
529
|
+
|
530
|
+
# Outputs a fieldset with a legend for the method label, and a ordered list (ol) of list
|
531
|
+
# items (li), one for each fragment for the time (hour, minute, second). Each li contains a label
|
532
|
+
# (eg "Hour") and a select box. See date_or_datetime_input for a more detailed output example.
|
533
|
+
#
|
534
|
+
# Some of Rails' options for select_time are supported, but not everything yet.
|
535
|
+
def time_input(method, options)
|
536
|
+
date_or_datetime_input(method, options.merge(:discard_year => true, :discard_month => true, :discard_day => true))
|
537
|
+
end
|
538
|
+
|
539
|
+
|
540
|
+
# <fieldset>
|
541
|
+
# <legend>Created At</legend>
|
542
|
+
# <ol>
|
543
|
+
# <li>
|
544
|
+
# <label for="user_created_at_1i">Year</label>
|
545
|
+
# <select id="user_created_at_1i" name="user[created_at(1i)]">
|
546
|
+
# <option value="2003">2003</option>
|
547
|
+
# ...
|
548
|
+
# <option value="2013">2013</option>
|
549
|
+
# </select>
|
550
|
+
# </li>
|
551
|
+
# <li>
|
552
|
+
# <label for="user_created_at_2i">Month</label>
|
553
|
+
# <select id="user_created_at_2i" name="user[created_at(2i)]">
|
554
|
+
# <option value="1">January</option>
|
555
|
+
# ...
|
556
|
+
# <option value="12">December</option>
|
557
|
+
# </select>
|
558
|
+
# </li>
|
559
|
+
# <li>
|
560
|
+
# <label for="user_created_at_3i">Day</label>
|
561
|
+
# <select id="user_created_at_3i" name="user[created_at(3i)]">
|
562
|
+
# <option value="1">1</option>
|
563
|
+
# ...
|
564
|
+
# <option value="31">31</option>
|
565
|
+
# </select>
|
566
|
+
# </li>
|
567
|
+
# </ol>
|
568
|
+
# </fieldset>
|
569
|
+
#
|
570
|
+
# This is an absolute abomination, but so is the official Rails select_date().
|
571
|
+
#
|
572
|
+
def date_or_datetime_input(method, options)
|
573
|
+
position = { :year => 1, :month => 2, :day => 3, :hour => 4, :minute => 5, :second => 6 }
|
574
|
+
inputs = options.delete(:order) || I18n.translate(:'date.order') || [:year, :month, :day]
|
575
|
+
time_inputs = [:hour, :minute]
|
576
|
+
time_inputs << [:second] if options[:include_seconds]
|
577
|
+
|
578
|
+
# Gets the datetime object. It can be a Fixnum, Date or Time, or nil.
|
579
|
+
datetime = @object.send(method)
|
580
|
+
|
581
|
+
list_items_capture = ""
|
582
|
+
(inputs + time_inputs).each do |input|
|
583
|
+
html_id = generate_html_id(method, "#{position[input]}i")
|
584
|
+
|
585
|
+
if options["discard_#{input}".intern]
|
586
|
+
break if time_inputs.include?(input)
|
587
|
+
hidden_value = datetime.respond_to?(input) ? datetime.send(input) : datetime
|
588
|
+
list_items_capture << template.hidden_field_tag("#{@object_name}[#{method}(#{position[input]}i)]", (hidden_value || 1), :id => html_id)
|
589
|
+
else
|
590
|
+
opts = set_options(options).merge(:prefix => @object_name, :field_name => "#{method}(#{position[input]}i)")
|
591
|
+
item_label_text = I18n.t(input.to_s, :default => input.to_s, :scope => [:formtastic]).send(@@label_str_method)
|
592
|
+
list_items_capture << template.content_tag(:li,
|
593
|
+
template.content_tag(:label, item_label_text, :for => html_id) +
|
594
|
+
template.send("select_#{input}".intern, @object.send(method), opts)
|
595
|
+
)
|
596
|
+
end
|
597
|
+
end
|
598
|
+
|
599
|
+
template.content_tag(:fieldset,
|
600
|
+
%{<legend><span>#{label_text(method, options)}</span></legend>} +
|
601
|
+
template.content_tag(:ol, list_items_capture)
|
602
|
+
)
|
603
|
+
end
|
604
|
+
|
605
|
+
# Outputs a label containing a checkbox and the label text. The label defaults to the column
|
606
|
+
# name (method name) and can be altered with the :label option.
|
607
|
+
def boolean_input(method, options)
|
608
|
+
input_label(method, options,
|
609
|
+
template.check_box(@object_name, method, set_options(options)) +
|
610
|
+
label_text(method, options)
|
611
|
+
)
|
612
|
+
end
|
613
|
+
|
614
|
+
# Outputs a label and select box containing two options for "true" and "false". The visible
|
615
|
+
# text defaults to "Yes" and "No" respectively, but can be altered with the :true and :false
|
616
|
+
# options. The label text to the column name (method name), but can be altered with the
|
617
|
+
# :label option. Example:
|
618
|
+
#
|
619
|
+
# f.input :awesome, :as => :boolean_select, :true => "Yeah!", :false => "Nah!", :label => "Make this sucker public?"
|
620
|
+
#
|
621
|
+
# Returns something like:
|
622
|
+
#
|
623
|
+
# <li class="boolean_select required" id="post_public_input">
|
624
|
+
# <label for="post_public">
|
625
|
+
# Make this sucker public?<abbr title="required">*</abbr>
|
626
|
+
# </label>
|
627
|
+
# <select id="post_public" name="post[public]">
|
628
|
+
# <option value="1">Yeah!</option>
|
629
|
+
# <option value="0">Nah!</option>
|
630
|
+
# </select>
|
631
|
+
# </li>
|
632
|
+
#
|
633
|
+
def boolean_select_input(method, options)
|
634
|
+
options[:true] ||= I18n.t('yes', :default => 'Yes', :scope => [:formtastic]).send(@@label_str_method)
|
635
|
+
options[:false] ||= I18n.t('no', :default => 'No', :scope => [:formtastic]).send(@@label_str_method)
|
636
|
+
|
637
|
+
choices = [ [options.delete(:true),true], [options.delete(:false),false] ]
|
638
|
+
input_label(method, options) + template.select(@object_name, method, choices, set_options(options))
|
639
|
+
end
|
640
|
+
|
641
|
+
# Outputs a fieldset containing two radio buttons (with labels) for "true" and "false". The
|
642
|
+
# visible label text for each option defaults to "Yes" and "No" respectively, but can be
|
643
|
+
# altered with the :true and :false options. The fieldset legend defaults to the column name
|
644
|
+
# (method name), but can be altered with the :label option. Example:
|
645
|
+
#
|
646
|
+
# f.input :awesome, :as => :boolean_radio, :true => "Yeah!", :false => "Nah!", :label => "Awesome?"
|
647
|
+
#
|
648
|
+
# Returns something like:
|
649
|
+
#
|
650
|
+
# <li class="boolean_radio required" id="post_public_input">
|
651
|
+
# <fieldset><legend><span>make this sucker public?<abbr title="required">*</abbr></span></legend>
|
652
|
+
# <ol>
|
653
|
+
# <li>
|
654
|
+
# <label for="post_public_true">
|
655
|
+
# <input id="post_public_true" name="post[public]" type="radio" value="true" /> Yeah!
|
656
|
+
# </label>
|
657
|
+
# </li>
|
658
|
+
# <li>
|
659
|
+
# <label for="post_public_false">
|
660
|
+
# <input id="post_public_false" name="post[public]" type="radio" checked="checked" /> Nah!
|
661
|
+
# </label>
|
662
|
+
# </li>
|
663
|
+
# </ol>
|
664
|
+
# </fieldset>
|
665
|
+
# </li>
|
666
|
+
def boolean_radio_input(method, options)
|
667
|
+
options[:true] ||= I18n.t('yes', :default => 'Yes', :scope => [:formtastic]).send(@@label_str_method)
|
668
|
+
options[:false] ||= I18n.t('no', :default => 'No', :scope => [:formtastic]).send(@@label_str_method)
|
669
|
+
|
670
|
+
choices = { options.delete(:true) => true, options.delete(:false) => false }
|
671
|
+
radio_input(method, { :collection => choices, :value_as_class => true }.merge(options))
|
672
|
+
end
|
673
|
+
|
674
|
+
def inline_errors(method, options) #:nodoc:
|
675
|
+
errors = @object.errors.on(method.to_s).to_a
|
676
|
+
unless errors.empty?
|
677
|
+
send("error_#{@@inline_errors}", errors) if [:sentence, :list].include?(@@inline_errors)
|
678
|
+
end
|
679
|
+
end
|
680
|
+
|
681
|
+
def error_sentence(errors) #:nodoc:
|
682
|
+
template.content_tag(:p, errors.to_sentence, :class => 'inline-errors')
|
683
|
+
end
|
684
|
+
|
685
|
+
def error_list(errors) #:nodoc:
|
686
|
+
list_elements = []
|
687
|
+
errors.each do |error|
|
688
|
+
list_elements << template.content_tag(:li, error)
|
689
|
+
end
|
690
|
+
template.content_tag(:ul, list_elements.join("\n"), :class => 'errors')
|
691
|
+
end
|
692
|
+
|
693
|
+
def inline_hints(method, options) #:nodoc:
|
694
|
+
options[:hint].blank? ? '' : template.content_tag(:p, options[:hint], :class => 'inline-hints')
|
695
|
+
end
|
696
|
+
|
697
|
+
def label_text(method, options) #:nodoc:
|
698
|
+
[ options[:label], required_or_optional_string(options[:required]) ].join()
|
699
|
+
end
|
700
|
+
|
701
|
+
def input_label(method, options, text = nil) #:nodoc:
|
702
|
+
text ||= label_text(method, options)
|
703
|
+
template.label(@object_name, method, text, set_options(options))
|
704
|
+
end
|
705
|
+
|
706
|
+
def required_or_optional_string(required) #:nodoc:
|
707
|
+
string_or_proc = required ? @@required_string : @@optional_string
|
708
|
+
|
709
|
+
if string_or_proc.is_a? Proc
|
710
|
+
string_or_proc.call
|
711
|
+
else
|
712
|
+
string_or_proc
|
713
|
+
end
|
714
|
+
end
|
715
|
+
|
716
|
+
def field_set_and_list_wrapping(field_set_html_options, contents = '', &block) #:nodoc:
|
717
|
+
legend_text = field_set_html_options.delete(:name)
|
718
|
+
legend = legend_text.blank? ? "" : template.content_tag(:legend, template.content_tag(:span, legend_text))
|
719
|
+
if block_given?
|
720
|
+
contents = template.capture(&block)
|
721
|
+
template.concat(
|
722
|
+
template.content_tag(:fieldset,
|
723
|
+
legend + template.content_tag(:ol, contents),
|
724
|
+
field_set_html_options
|
725
|
+
)
|
726
|
+
)
|
727
|
+
else
|
728
|
+
template.content_tag(:fieldset,
|
729
|
+
legend + template.content_tag(:ol, contents),
|
730
|
+
field_set_html_options
|
731
|
+
)
|
732
|
+
end
|
733
|
+
|
734
|
+
end
|
735
|
+
|
736
|
+
# For methods that have a database column, take a best guess as to what the inout method
|
737
|
+
# should be. In most cases, it will just return the column type (eg :string), but for special
|
738
|
+
# cases it will simplify (like the case of :integer, :float & :decimal to :numeric), or do
|
739
|
+
# something different (like :password and :select).
|
740
|
+
#
|
741
|
+
# If there is no column for the method (eg "virtual columns" with an attr_accessor), the
|
742
|
+
# default is a :string, a similar behaviour to Rails' scaffolding.
|
743
|
+
def default_input_type(object, method) #:nodoc:
|
744
|
+
# Find the column object by attribute
|
745
|
+
column = object.column_for_attribute(method) if object.respond_to?(:column_for_attribute)
|
746
|
+
# Maybe the column is a reflection?
|
747
|
+
column = find_reflection(method) unless column
|
748
|
+
|
749
|
+
if column
|
750
|
+
# handle the special cases where the column type doesn't map to an input method
|
751
|
+
return :select if column.respond_to?(:macro) && column.respond_to?(:klass)
|
752
|
+
return :select if column.type == :integer && method.to_s =~ /_id$/
|
753
|
+
return :datetime if column.type == :timestamp
|
754
|
+
return :numeric if [:integer, :float, :decimal].include?(column.type)
|
755
|
+
return :password if column.type == :string && method.to_s =~ /password/
|
756
|
+
# otherwise assume the input name will be the same as the column type (eg string_input)
|
757
|
+
return column.type
|
758
|
+
else
|
759
|
+
obj = object.send(method)
|
760
|
+
return :file if [:file?, :public_filename].any? { |m| obj.respond_to?(m) }
|
761
|
+
return :password if method.to_s =~ /password/
|
762
|
+
return :string
|
763
|
+
end
|
764
|
+
end
|
765
|
+
|
766
|
+
# Used by association inputs (select, radio) to get a default collection from the parent object
|
767
|
+
# by determining the classname from the method/column name (section_id => Section) and doing a
|
768
|
+
# simple find(:all).
|
769
|
+
def find_parent_objects_for_column(column)
|
770
|
+
parent_class = if reflection = find_reflection(column)
|
771
|
+
reflection.klass
|
772
|
+
else
|
773
|
+
::ActiveSupport::Deprecation.warn("The _id way of doing things is deprecated. Please use the association method (#{column.to_s.sub(/_id$/,'')})", caller[3..-1])
|
774
|
+
column.to_s.sub(/_id$/,'').camelize.constantize
|
775
|
+
end
|
776
|
+
parent_class.find(:all)
|
777
|
+
end
|
778
|
+
|
779
|
+
# Used by association inputs (select, radio) to generate the name that should be used for the input
|
780
|
+
# belongs_to :author; f.input :author; will generate 'author_id'
|
781
|
+
# has_many :authors; f.input :authors; will generate 'author_ids'
|
782
|
+
# has_and_belongs_to_many will act like has_many
|
783
|
+
def generate_association_input_name(method)
|
784
|
+
if reflection = find_reflection(method)
|
785
|
+
method = "#{method.to_s.singularize}_id"
|
786
|
+
method = method.pluralize if [:has_and_belongs_to_many, :has_many].include?(reflection.macro)
|
787
|
+
end
|
788
|
+
method
|
789
|
+
end
|
790
|
+
|
791
|
+
# If an association method is passed in (f.input :author) try to find the reflection object
|
792
|
+
def find_reflection(method)
|
793
|
+
object.class.reflect_on_association(method) if object.class.respond_to?(:reflect_on_association)
|
794
|
+
end
|
795
|
+
|
796
|
+
def default_string_options(method) #:nodoc:
|
797
|
+
# Use rescue to set column if @object does not have a column_for_attribute method
|
798
|
+
# (eg if @object is not an ActiveRecord object)
|
799
|
+
begin
|
800
|
+
column = @object.column_for_attribute(method)
|
801
|
+
rescue NoMethodError
|
802
|
+
column = nil
|
803
|
+
end
|
804
|
+
opts = if column.nil? || column.limit.nil?
|
805
|
+
{ :size => @@default_text_field_size }
|
806
|
+
else
|
807
|
+
{ :maxlength => column.limit, :size => [column.limit, @@default_text_field_size].min }
|
808
|
+
end
|
809
|
+
set_options(opts)
|
810
|
+
end
|
811
|
+
|
812
|
+
# Generate the html id for the li tag.
|
813
|
+
# It takes into account options[:index] and @auto_index to generate li
|
814
|
+
# elements with appropriate index scope. It also sanitizes the object
|
815
|
+
# and method names.
|
816
|
+
#
|
817
|
+
def generate_html_id(method_name, value='input')
|
818
|
+
if options.has_key?(:index)
|
819
|
+
index = "_#{options[:index]}"
|
820
|
+
elsif defined?(@auto_index)
|
821
|
+
index = "_#{@auto_index}"
|
822
|
+
else
|
823
|
+
index = ""
|
824
|
+
end
|
825
|
+
sanitized_method_name = method_name.to_s.sub(/\?$/,"")
|
826
|
+
|
827
|
+
"#{sanitized_object_name}#{index}_#{sanitized_method_name}_#{value}"
|
828
|
+
end
|
829
|
+
|
830
|
+
def sanitized_object_name
|
831
|
+
@sanitized_object_name ||= @object_name.to_s.gsub(/\]\[|[^-a-zA-Z0-9:.]/, "_").sub(/_$/, "")
|
832
|
+
end
|
833
|
+
|
834
|
+
end
|
835
|
+
|
836
|
+
# Wrappers around form_for (etc) with :builder => SemanticFormBuilder.
|
837
|
+
#
|
838
|
+
# * semantic_form_for(@post)
|
839
|
+
# * semantic_fields_for(@post)
|
840
|
+
# * semantic_form_remote_for(@post)
|
841
|
+
# * semantic_remote_form_for(@post)
|
842
|
+
#
|
843
|
+
# Each of which are the equivalent of:
|
844
|
+
#
|
845
|
+
# * form_for(@post, :builder => Formtastic::SemanticFormBuilder))
|
846
|
+
# * fields_for(@post, :builder => Formtastic::SemanticFormBuilder))
|
847
|
+
# * form_remote_for(@post, :builder => Formtastic::SemanticFormBuilder))
|
848
|
+
# * remote_form_for(@post, :builder => Formtastic::SemanticFormBuilder))
|
849
|
+
#
|
850
|
+
# Example Usage:
|
851
|
+
#
|
852
|
+
# <% semantic_form_for @post do |f| %>
|
853
|
+
# <%= f.input :title %>
|
854
|
+
# <%= f.input :body %>
|
855
|
+
# <% end %>
|
856
|
+
#
|
857
|
+
# The above examples use a resource-oriented style of form_for() helper where only the @post
|
858
|
+
# object is given as an argument, but the generic style is also supported if you really want it,
|
859
|
+
# as is forms with inline objects (Post.new) rather than objects with instance variables (@post):
|
860
|
+
#
|
861
|
+
# <% semantic_form_for :post, @post, :url => posts_path do |f| %>
|
862
|
+
# ...
|
863
|
+
# <% end %>
|
864
|
+
#
|
865
|
+
# <% semantic_form_for :post, Post.new, :url => posts_path do |f| %>
|
866
|
+
# ...
|
867
|
+
# <% end %>
|
868
|
+
#
|
869
|
+
# The shorter, resource-oriented style is most definitely preferred, and has recieved the most
|
870
|
+
# testing to date.
|
871
|
+
#
|
872
|
+
# Please note: Although it's possible to call Rails' built-in form_for() helper without an
|
873
|
+
# object, all semantic forms *must* have an object (either Post.new or @post), as Formtastic
|
874
|
+
# has too many dependencies on an ActiveRecord object being present.
|
875
|
+
module SemanticFormHelper
|
876
|
+
@@builder = Formtastic::SemanticFormBuilder
|
877
|
+
|
878
|
+
# cattr_accessor :builder
|
879
|
+
def self.builder=(val)
|
880
|
+
@@builder = val
|
881
|
+
end
|
882
|
+
|
883
|
+
[:form_for, :fields_for, :form_remote_for, :remote_form_for].each do |meth|
|
884
|
+
src = <<-END_SRC
|
885
|
+
def semantic_#{meth}(record_or_name_or_array, *args, &proc)
|
886
|
+
options = args.extract_options!
|
887
|
+
options[:builder] = @@builder
|
888
|
+
options[:html] ||= {}
|
889
|
+
|
890
|
+
class_names = options[:html][:class] ? options[:html][:class].split(" ") : []
|
891
|
+
class_names << "formtastic"
|
892
|
+
class_names << case record_or_name_or_array
|
893
|
+
when String, Symbol then record_or_name_or_array.to_s # :post => "post"
|
894
|
+
when Array then record_or_name_or_array.last.class.to_s.underscore # [@post, @comment] # => "comment"
|
895
|
+
else record_or_name_or_array.class.to_s.underscore # @post => "post"
|
896
|
+
end
|
897
|
+
options[:html][:class] = class_names.join(" ")
|
898
|
+
|
899
|
+
#{meth}(record_or_name_or_array, *(args << options), &proc)
|
900
|
+
end
|
901
|
+
END_SRC
|
902
|
+
module_eval src, __FILE__, __LINE__
|
903
|
+
end
|
904
|
+
end
|
905
|
+
end
|