Permalink
Newer
Older
100644 529 lines (390 sloc) 21.4 KB
Apr 7, 2008
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
Apr 7, 2008
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:
Apr 7, 2008
8
10
<% semantic_form_for @article do |form| %>
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 :category %>
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 %>
28
<% form.inputs :name => "Author", :for => :author do |author_form| %>
29
<%= author_form.input :first_name %>
30
<%= author_form.input :last_name %>
33
<% form.buttons do %>
34
<%= form.commit_button %>
Apr 7, 2008
37
<% end %>
40
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.
Apr 7, 2008
41
42
43
h2. It's better than _SomeOtherFormBuilder_ because...
44
45
* 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
46
* 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
47
* it's Rails 2.3-ready (including nested forms)
48
* it has internationalization (I18n)!
49
* 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
50
* there's heaps of elements, id and class attributes for you to hook in your CSS and JS
@justinfrench
Mar 3, 2009
51
* it handles real world stuff like inline hints, inline error messages & help text
52
* 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)
53
* it's got absolutely awesome spec coverage
54
* there's a bunch of people using and working on it (it's not just one developer building half a solution)
57
h2. Why?
58
59
* web apps = lots of forms
60
* forms are so friggin' boring to code
61
* semantically rich & accessible forms really are possible
62
* the "V" is way behind the "M" and "C" in Rails' MVC – it's the ugly sibling
Apr 7, 2008
63
* best practices and common patterns have to start somewhere
64
* i need a challenge
Apr 7, 2008
65
66
67
h2. Opinions
68
69
* it should be easier to do things the right way than the wrong way
70
* sometimes _more mark-up_ is better
71
* elements and attribute hooks are _gold_ for stylesheet authors
72
* make the common things we do easy, yet still ensure uncommon things are still possible
73
Apr 7, 2008
74
75
h2. Documentation
76
77
RDoc documentation _should_ be automatically generated after each commit and made available on the "rdoc.info website":http://rdoc.info/projects/justinfrench/formtastic.
78
79
82
You can and should get it as a gem:
83
84
<pre>
85
gem install justinfrench-formtastic
86
</pre>
87
88
And then add it as a dependency in your environment.rb file:
89
90
<pre>
91
config.gem "justinfrench-formtastic",
92
:lib => 'formtastic',
93
:source => 'http://gems.github.com'
96
If you want, run the generator to copy the following files into your app:
97
98
* config/initializers/formtastic.rb (a commented out Formtastic config initializer)
99
* public/stylesheets/formtastic.css
100
* public/stylesheets/formtastic_changes.css
104
</pre
105
106
A proof-of-concept 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. If you want to use these stylesheets, add both to your layout:
108
<pre>
109
<%= stylesheet_link_tag "formtastic" %>
110
<%= stylesheet_link_tag "formtastic_changes" %>
111
</pre>
114
h2. Usage
115
116
Forms are really boring to code... you want to get onto the good stuff as fast as possible.
117
118
This renders a set of inputs (one for _most_ columns in the database table, and one for each ActiveRecord belongs_to association), followed by a submit button:
119
120
<pre>
121
<% semantic_form_for @user do |form| %>
122
<%= form.inputs %>
123
<%= form.buttons %>
124
<% end %>
125
</pre>
126
127
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@:
128
129
<pre>
130
<% semantic_form_for @user do |form| %>
131
<%= form.inputs :title, :body, :section, :categories, :created_at %>
132
<%= form.buttons :commit %>
133
<% end %>
134
</pre>
135
136
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):
137
138
<pre>
139
<% semantic_form_for @post do |form| %>
140
<% form.inputs do %>
141
<%= form.input :title %>
142
<%= form.input :body %>
143
<%= form.input :section, :as => :radio %>
144
<%= form.input :categories %>
145
<%= form.input :created_at, :as => :string %>
146
<% end %>
147
<% form.buttons do %>
148
<%= form.commit_button %>
149
<% end %>
150
<% end %>
151
</pre>
152
@justinfrench
Apr 19, 2009
153
If you want to customize the label text, or render some hint text below the field, specify which fields are required/optional, or break the form into two fieldsets, the DSL is pretty comprehensive:
154
155
<pre>
156
<% semantic_form_for @post do |form| %>
157
<% form.inputs :name => "Basic", :id => "basic" do %>
158
<%= form.input :title %>
159
<%= form.input :body %>
160
<% end %>
161
<% form.inputs :name => "Advanced Options", :id => "advanced" do %>
162
<%= form.input :slug, :label => "URL Title", :hint => "Created automatically if left blank", :required => false %>
163
<%= form.input :section, :as => :radio %>
164
<%= form.input :user, :label => "Author", :label_method => :full_name, %>
165
<%= form.input :categories, :required => false %>
166
<%= form.input :created_at, :as => :string, :label => "Publication Date", :required => false %>
167
<% end %>
168
<% form.buttons do %>
169
<%= form.commit_button %>
170
<% end %>
171
<% end %>
172
</pre>
173
175
Nested forms (Rails 2.3) are also supported. You can do it in the Rails way:
178
<% semantic_form_for @post do |form| %>
179
<%= form.inputs :title, :body, :created_at %>
@josevalim
Mar 23, 2009
180
<% form.semantic_fields_for :author do |author| %>
181
<%= author.inputs :first_name, :last_name, :name => 'Author' %>
@josevalim
Mar 23, 2009
182
<% end %>
183
<%= form.buttons %>
184
<% end %>
185
</pre>
186
187
Or the Formtastic way with the @:for@ option:
190
<% semantic_form_for @post do |form| %>
191
<%= form.inputs :title, :body, :created_at %>
192
<%= form.inputs :first_name, :last_name, :for => :author, :name => "Author" %>
193
<%= form.buttons %>
194
<% end %>
195
</pre>
196
197
When working in has many association, you can even supply "%i" in your fieldset name that it will be properly interpolated with the child index. For example:
198
199
<pre>
200
<% semantic_form_for @post do |form| %>
201
<%= form.inputs %>
202
<%= form.inputs :name => 'Category #%i', :for => :categories %>
203
<%= form.buttons %>
204
<% end %>
205
</pre>
206
207
208
Customize HTML attributes for any input using the @:input_html@ option. Typically his is used to disable the input, change the size of a text field, change the rows in a textarea, or even to add a special class to an input to attach special behavior like "autogrow":http://plugins.jquery.com/project/autogrow textareas:
209
210
<pre>
211
<% semantic_form_for @post do |form| %>
212
<%= form.input :title, :input_html => { :size => 60 } %>
213
<%= form.input :body, :input_html => { :class => 'autogrow' } %>
214
<%= form.input :created_at, :input_html => { :disabled => true } %>
215
<%= form.buttons %>
216
<% end %>
217
</pre>
218
219
The same can be done for buttons with the @:button_html@ option:
220
221
<pre>
222
<% semantic_form_for @post do |form| %>
223
...
224
<% form.buttons do %>
225
<%= form.commit_button :button_html => { :class => "primary" } %>
226
<% end %>
227
<% end %>
228
</pre>
229
230
Customize the HTML attributes for the @<li>@ wrapper around every input with the @:wrapper_html@ option hash. There's one special key in the hash (:class), which will actually _append_ your string of classes to the existing classes provided by Formtastic (like "required string error")
231
232
<pre>
233
<% semantic_form_for @post do |form| %>
234
<%= form.input :title, :wrapper_html => { :class => "important" } %>
235
<%= form.input :body %>
236
<%= form.input :description, :wrapper_html => { :style => "display:none;" } %>
237
...
238
<% end %>
239
</pre>
240
241
245
* :select (a select menu) - default for ActiveRecord associations (belongs_to, has_many, has_and_belongs_to_many)
246
* :check_boxes (a set of check_box inputs) - alternative to :select has_many and has_and_belongs_to_many associations
247
* :radio (a set of radio inputs) - alternative to :select for ActiveRecord belongs_to associations
248
* :time_zone (a select input) - default for :string column types with 'time_zone' in the method name
249
* :password (a password input) - default for :string column types with 'password' in the method name
250
* :text (a textarea) - default for :text column types
251
* :date (a date select) - default for :date column types
252
* :datetime (a date and time select) - default for :datetime and :timestamp column types
253
* :time (a time select) - default for :time column types
254
* :boolean (a checkbox) - default for :boolean column types
255
* :string (a text field) - default for :string column types
256
* :numeric (a text field, like string) - default for :integer, :float and :decimal column types
257
* :file (a file field) - default for paperclip or attachment_fu attributes
258
* :country (a select menu of country names) - default for :string columns named "country", requires a country_select plugin to be installed
259
* :hidden (a hidden field) - creates a hidden field (added for compatibility)
262
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.
264
h2. Internationalization (I18n)
265
266
Formtastic got some neat I18n-features. 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. See lib/locale/en.yml for more information.
267
268
h3. Label/Hint-localization
269
270
Formtastic supports localized *labels* and *hints* using the I18n API for more advanced usage. Your forms can now be DRYer and more flexible than ever, and still fully localized. This is how:
271
272
Basic localization (labels only, with ActiveRecord):
273
274
<pre>
275
<% semantic_form_for @post do |form| %>
276
<%= form.input :title %> # => :label => I18n.t('activerecord.attributes.user.title') or 'Title'
277
<%= form.input :body %> # => :label => I18n.t('activerecord.attributes.user.body') or 'Body'
278
<%= form.input :section %> # => :label => I18n.t('activerecord.attributes.user.section') or 'Section'
279
<% end %>
280
</pre>
281
282
*Note:* This is perfectly fine if you just want your labels to be translated using *ActiveRecord I18n attribute translations*, and you don't use input hints. But what if you do? And what if you don't want same labels in all forms?
283
284
Enhanced localization (labels + hints + titles/legends, with Formtastic):
285
286
1. Enable I18n lookups by default (@config/initializers/formtastic.rb@):
287
288
<pre>
289
Formtastic::SemanticFormBuilder.i18n_lookups_by_default = true
290
</pre>
291
292
2. Add some cool label-translations/variants (@config/locale/en.yml@):
293
294
<pre>
295
en:
296
formtastic:
297
titles:
298
post_details: "Post details"
299
labels:
300
post:
301
title: "Choose a title..."
302
body: "Write something..."
305
hints:
306
post:
307
title: "Choose a good title for you post."
308
body: "Write something inspiring here."
309
</pre>
310
311
*Note:* We are using English here still, but you get the point.
312
313
3. ...and now you'll get:
314
315
<pre>
316
<% semantic_form_for @post do |form| %>
317
<% inputs do %>
318
<%= form.input :title %> # => :label => "Choose a title...", :hint => "Choose a good title for you post."
319
<%= form.input :body %> # => :label => "Write something...", :hint => "Write something inspiring here."
320
<%= form.input :section %> # => :label => I18n.t('activerecord.attributes.user.section') or 'Section'
321
<% end %>
322
...
323
<% end %>
324
</pre>
325
326
4. Localized titles (a.k.a. legends):
327
328
_Note: Slightly different because Formtastic can't guess how you group fields in a form._
329
330
<pre>
331
<% semantic_form_for @post do |form| %>
332
<% inputs :title => :post_details do %> # => :title => "Post details"
333
# ...
334
<% end %>
335
# ...
336
<% end %>
337
</pre>
338
339
5. Override I18n settings:
340
341
<pre>
342
<% semantic_form_for @post do |form| %>
343
<% inputs do %>
344
<%= form.input :title %> # => :label => "Choose a title...", :hint => "Choose a good title for you post."
345
<%= form.input :body, :hint => false %> # => :label => "Write something..."
346
<%= form.input :section, :label => 'Some section' %> # => :label => 'Some section'
347
<% end %>
348
# ...
349
<% end %>
350
</pre>
351
352
If I18n-lookups is disabled, i.e.:
353
354
<pre>
355
Formtastic::SemanticFormBuilder.i18n_lookups_by_default = false
356
</pre>
357
358
...then you can enable I18n within the forms instead:
359
360
<pre>
361
<% semantic_form_for @post do |form| %>
362
<% inputs do %>
363
<%= form.input :title, :label => true %> # => :label => "Choose a title..."
364
<%= form.input :body, :label => true %> # => :label => "Write something..."
365
<%= form.input :section, :label => true %> # => :label => I18n.t('activerecord.attributes.user.section') or 'Section'
366
<% end %>
367
# ...
368
<% end %>
369
</pre>
370
372
373
For more flexible forms; Formtastic find translations using a bottom-up approach taking the following variables in account:
374
375
* @MODEL@, e.g. "post"
376
* @ACTION@, e.g. "edit"
377
* @ATTRIBUTE@, e.g. "title"
378
379
...in the following order:
380
381
1. @formtastic.{titles,labels,hints}.MODEL.ACTION.ATTRIBUTE@ # By model and action
382
2. @formtastic.{titles,labels,hints}.MODEL.ATTRIBUTE@ # By model
383
3. @formtastic.{titles,labels,hints}.ATTRIBUTE@ # Global default
384
385
...which means that you can define translations like this:
386
387
<pre>
388
en:
389
formtastic:
390
labels:
391
title: "Title" # Default global value
392
article:
393
body: "Article content"
394
post:
395
new:
396
title: "Choose a title..."
397
body: "Write something..."
398
edit:
399
title: "Edit title"
400
body: "Edit body"
401
</pre>
402
403
*Note:* For @title@: ATTRIBUTE is a KEY chosen by you, e.g. in step 4 example above: @:post_details@.
404
405
h2. ValidationReflection plugin
406
407
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).
408
409
h2. Configuration
410
411
If you wish, put something like this in config/initializers/formtastic_config.rb:
412
413
<pre>
414
# Set the default text field size when input is a string. Default is 50
415
Formtastic::SemanticFormBuilder.default_text_field_size = 30
416
417
# Should all fields be considered "required" by default
418
# Defaults to true, see ValidationReflection notes below
419
Formtastic::SemanticFormBuilder.all_fields_required_by_default = false
420
421
# Set the string that will be appended to the labels/fieldsets which are required
422
# It accepts string or procs and the default is a localized version of
423
# '<abbr title="required">*</abbr>'. In other words, if you configure formtastic.required
424
# in your locale, it will replace the abbr title properly. But if you don't want to use
425
# abbr tag, you can simply give a string as below
426
Formtastic::SemanticFormBuilder.required_string = "(required)"
427
428
# Set the string that will be appended to the labels/fieldsets which are optional
429
# Defaults to an empty string ("") and also accepts procs (see required_string above)
430
Formtastic::SemanticFormBuilder.optional_string = "(optional)"
432
# Set the way inline errors will be displayed.
@justinfrench
Feb 16, 2009
433
# Defaults to :sentence, valid options are :sentence, :list and :none
434
Formtastic::SemanticFormBuilder.inline_errors = :list
@sprsquish
Feb 16, 2009
435
436
# Set the method to call on label text to transform or format it for human-friendly
437
# reading when formtastic is user without object. Defaults to :humanize.
@sprsquish
Feb 16, 2009
438
Formtastic::SemanticFormBuilder.label_str_method = :titleize
440
# Set the array of methods to try calling on parent objects in :select and :radio inputs
441
# for the text inside each @<option>@ tag or alongside each radio @<input>@. The first method
442
# that is found on the object will be used.
443
# Defaults to ["to_label", "display_name", "full_name", "name", "title", "username", "login", "value", "to_s"]
444
Formtastic::SemanticFormBuilder.collection_label_methods = ["title_and_author", "display_name", "login", "to_s"]
445
446
# Formtastic by default renders inside li tags the input, hints and then
447
# errors messages. Sometimes you want the hints to be rendered first than
448
# the input, in the following order: hints, input and errors. You can
449
# customize it doing just as below:
450
Formtastic::SemanticFormBuilder.inline_order = [:hints, :input, :errors]
451
452
# Set the default "priority countries" to suit your user base when using :as => :country
453
Formtastic::SemanticFormBuilder.priority_countries = ["Australia", "New Zealand"]
454
455
# Specifies if labels/hints for input fields automatically be looked up using I18n.
456
# Default value: false. Overridden for specific fields by setting value to true,
457
# i.e. :label => true, or :hint => true (or opposite depending on initialized value)
458
# Formtastic::SemanticFormBuilder.i18n_lookups_by_default = false
459
460
# If you want to subclass SemanticFormBuilder to add/change the behavior to suit your needs, you
461
# can specify the builder class.
462
# Formtastic::SemanticFormHelper.builder = MyCustomBuilder
Apr 7, 2008
466
467
*THINGS ARE GOING TO CHANGE A BIT BEFORE WE HIT 1.0.*
Apr 7, 2008
468
469
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.
470
471
On the plus side, it has a comprehensive spec suite and contributions from at least ten independent developers.
Apr 7, 2008
472
473
"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.
Apr 7, 2008
475
476
h2. Dependencies
Apr 7, 2008
477
478
There are none, but...
Apr 7, 2008
479
480
* 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)
481
* if you want to use the :country input, you'll need to install the "iso-3166-country-select plugin":http://github.com/rails/iso-3166-country-select (or any other country_select plugin with the same API)
482
* rspec, rspec_hpricot_matchers and rcov gems (plus any of their own dependencies) are required for the test suite
Apr 7, 2008
483
485
h2. Compatibility
487
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!
490
h2. Got TextMate?
491
492
Well...there's a TextMate-bundle in town, dedicated to make usage of Formtastic in the TextMate editor even more of a breeze:
493
494
"Formtastic.tmbundle":http://github.com/grimen/formtastic_tmbundle
496
h2. Contributors
497
498
Formtastic is maintained by "Justin French":http://justinfrench.com and "José Valim":http://github.com/josevalim, but it wouldn't be as awesome as it is today if it weren't for the wonderful contributions of these fine, fine coders.
500
* "Jeff Smick":http://github.com/sprsquish
501
* "Tien Dung":http://github.com/tiendung
502
* "Mark Mansour":http://stateofflux.com
503
* "Andy Pearson":http://github.com/andypearson
504
* "negonicrac":http://github.com/negonicrac
506
* "Pat Allan":http://github.com/freelancing-god
507
* "Gareth Townsend":http://github.com/quamen
508
* "Sascha Hoellger":http://github.com/mitnal
509
* "Andrew Carpenter":http://github.com/andrewcarpenter
510
* "Jack Dempsey":http://github.com/jackdempsey/
511
* "Greg Fitzgerald":http://github.com/gregf/
512
* "Hector E. Gomez Morales":http://github.com/hectoregm
513
* "Ben Hamill":http://blog.benhamill.com/
514
* "Simon Chiu":http://github.com/tolatomeow
515
* "Bin Dong":http://github.com/dongbin
517
518
h2. Hey, join the Google group!
519
520
Please join the "Formtastic Google Group":http://groups.google.com.au/group/formtastic, especially if you'd like to talk about a new feature, or report a bug.
521
522
@justinfrench
Dec 8, 2008
525
Formtastic is hosted on Github: http://github.com/justinfrench/formtastic/, where your contributions, forkings, comments and feedback are greatly welcomed.
528
Copyright (c) 2007-2008 Justin French, released under the MIT license.