Skip to content
Newer
Older
100644 550 lines (402 sloc) 20.2 KB
61fc74b @olivierlacan Converted README to GitHub-flavored Markdown w/ syntax highlighting f…
olivierlacan authored Sep 23, 2011
1 # SimpleForm
2 ## Rails forms made easy.
3
4 SimpleForm aims to be as flexible as possible while helping you with powerful components to create your forms. The basic goal of simple form is to not touch your way of defining the layout, letting you find the better design for your eyes. Good part of the DSL was inherited from Formtastic, which we are thankful for and should make you feel right at home.
5
6 ## Information
7
8 ### Google Group
9
10 If you have any questions, comments, or concerns please use the Google Group instead of the GitHub Issues tracker:
11
12 http://groups.google.com/group/plataformatec-simpleform
13
14 ### RDocs
15
16 You can view the SimpleForm documentation in RDoc format here:
17
18 http://rubydoc.info/github/plataformatec/simple_form/master/frames
19
20 If you need to use SimpleForm with Rails 2.3, you can always run `gem server` from the command line after you install the gem to access the old documentation.
21
22 ### Bug reports
23
24 If you discover any bugs, feel free to create an issue on GitHub. Please add as much information as possible to help us fixing the possible bug. We also encourage you to help even more by forking and sending us a pull request.
25
26 http://github.com/plataformatec/simple_form/issues
27
28 ## Installation
29
30 Install the gem:
31
32 `gem install simple_form`
33
34 Add it to your Gemfile:
35
36 `gem "simple_form"`
37
38 Run the generator:
39
40 `rails generate simple_form:install`
41
42 Also, if you want to use the country select, you will need the country_select plugin, install with following command:
43
44 `rails plugin install git://github.com/rails/country_select.git`
45
46 And you are ready to go. Since this branch aims Rails 3 support,
47 if you want to use it with Rails 2.3 you should check this branch:
48
49 `http://github.com/plataformatec/simple_form/tree/v1.0`
50
51 ## Usage
52
53 SimpleForm was designed to be customized as you need to. Basically it's a stack of components that are invoked to create a complete html input for you, which by default contains label, hints, errors and the input itself. It does not aim to create a lot of different logic from the default Rails form helpers, as they do a great work by themselves. Instead, SimpleForm acts as a DSL and just maps your input type (retrieved from the column definition in the database) to an specific helper method.
54
55 To start using SimpleForm you just have to use the helper it provides:
56
57 ```erb
58 <%= simple_form_for @user do |f| %>
59 <%= f.input :username %>
60 <%= f.input :password %>
61 <%= f.button :submit %>
62 <% end %>
63 ```
64
65 This will generate an entire form with labels for user name and password as well, and render errors by default when you render the form with invalid data (after submitting for example).
66
67 You can overwrite the default label by passing it to the input method, add a hint or even a placeholder:
68
69 ```erb
70 <%= simple_form_for @user do |f| %>
71 <%= f.input :username, :label => 'Your username please' %>
72 <%= f.input :password, :hint => 'No special characters.' %>
73 <%= f.input :email, :placeholder => 'user@domain.com' %>
74 <%= f.button :submit %>
75 <% end %>
76 ```
77
78 You can also disable labels, hints or error or configure the html of any of them:
79
80 ```erb
81 <%= simple_form_for @user do |f| %>
82 <%= f.input :username, :label_html => { :class => 'my_class' } %>
83 <%= f.input :password, :hint => false, :error_html => { :id => "password_error"} %>
84 <%= f.input :password_confirmation, :label => false %>
85 <%= f.button :submit %>
86 <% end %>
87 ```
88
89 It is also possible to pass any html attribute straight to the input, by using the :input_html option, for instance:
90
91 ```erb
92 <%= simple_form_for @user do |f| %>
93 <%= f.input :username, :input_html => { :class => 'special' } %>
94 <%= f.input :password, :input_html => { :maxlength => 20 } %>
95 <%= f.input :remember_me, :input_html => { :value => '1' } %>
96 <%= f.button :submit %>
97 <% end %>
98 ```
99
8ee50d8 @olivierlacan Added :wrapper_html example to the README.
olivierlacan authored Sep 28, 2011
100 Since simple_form generates a wrapper div around your label and input by default, you can pass any html attribute to that wrapper as well using the :wrapper_html option, like so:
101
102 ```erb
103 <%= simple_form_for @user do |f| %>
104 <%= f.input :username, :wrapper_html => { :class => 'username' } %>
105 <%= f.input :password, :wrapper_html => { :id => 'password' } %>
106 <%= f.input :remember_me, :wrapper_html => { :class => 'options' } %>
107 <%= f.button :submit %>
108 <% end %>
109 ```
110
61fc74b @olivierlacan Converted README to GitHub-flavored Markdown w/ syntax highlighting f…
olivierlacan authored Sep 23, 2011
111 By default all inputs are required, which means an * is prepended to the label, but you can disable it in any input you want:
112
113 ```erb
114 <%= simple_form_for @user do |f| %>
115 <%= f.input :name, :required => false %>
116 <%= f.input :username %>
117 <%= f.input :password %>
118 <%= f.button :submit %>
119 <% end %>
120 ```
121
122 SimpleForm also lets you overwrite the default input type it creates:
123
124 ```erb
125 <%= simple_form_for @user do |f| %>
126 <%= f.input :username %>
127 <%= f.input :password %>
128 <%= f.input :description, :as => :text %>
129 <%= f.input :accepts, :as => :radio %>
130 <%= f.button :submit %>
131 <% end %>
132 ```
133
134 So instead of a checkbox for the :accepts attribute, you'll have a pair of radio buttons with yes/no labels and a text area instead of a text field for the description. You can also render boolean attributes using :as => :select to show a dropdown.
135
136 It is also possible to give the :disabled option to SimpleForm, and it'll automatically mark the wrapper as disabled with a css class, so you can style labels, hints and other components inside the wrapper as well:
137
138 ```erb
139 <%= simple_form_for @user do |f| %>
140 <%= f.input :username, :disabled => true, :hint => "You cannot change your username." %>
141 <%= f.button :submit %>
142 <% end %>
143 ```
144
145 SimpleForm accepts same options as their corresponding input type helper in Rails:
146
147 ```erb
148 <%= simple_form_for @user do |f| %>
149 <%= f.input :date_of_birth, :as => :date, :start_year => Date.today.year - 90,
150 :end_year => Date.today.year - 12, :discard_day => true,
151 :order => [:month, :year] %>
152 <%= f.button :submit %>
153 <% end %>
154 ```
155
156 SimpleForm also allows you to use label, hint, input_field, error and full_error helpers it provides (please take a look at the rdocs for each method for more info):
157
158 ```erb
159 <%= simple_form_for @user do |f| %>
160 <%= f.label :username %>
161 <%= f.input_field :username %>
162 <%= f.hint 'No special characters, please!' %>
163 <%= f.error :username, :id => 'user_name_error' %>
164 <%= f.full_error :token %>
165 <%= f.submit 'Save' %>
166 <% end %>
167 ```
168
169 Any extra option passed to these methods will be rendered as html option.
170
171 ### Collections
172
173 And what if you want to create a select containing the age from 18 to 60 in your form? You can do it overriding the :collection option:
174
175 ```erb
176 <%= simple_form_for @user do |f| %>
177 <%= f.input :user %>
178 <%= f.input :age, :collection => 18..60 %>
179 <%= f.button :submit %>
180 <% end %>
181 ```
182
183 Collections can be arrays or ranges, and when a :collection is given the :select input will be rendered by default, so we don't need to pass the :as => :select option. Other types of collection are :radio and :check_boxes. Those are added by SimpleForm to Rails set of form helpers (read Extra Helpers session below for more information).
184
185 Collection inputs accepts two other options beside collections:
186
187 * label_method => the label method to be applied to the collection to retrieve the label
188
189 * value_method => the value method to be applied to the collection to retrieve the value
190
191 Those methods are useful to manipulate the given collection. Both of these options also accept lambda/procs in case you want to calculate the value or label in a special way eg. custom translation. All other options given are sent straight to the underlying helper. For example, you can give prompt as:
192
193 ```ruby
194 f.input :age, :collection => 18..60, :prompt => "Select your age"
195 ```
196
197 ### Priority
198
199 SimpleForm also supports :time_zone and :country. When using such helpers, you can give :priority as option to select which time zones and/or countries should be given higher priority:
200
201 ```ruby
202 f.input :residence_country, :priority => [ "Brazil" ]
203 f.input :time_zone, :priority => /US/
204 ```
205
206 Those values can also be configured with a default value to be used site use through the SimpleForm.country_priority and SimpleForm.time_zone_priority helpers.
207
208 ### Wrapper
209
210 SimpleForm allows you to add a wrapper which contains the label, error, hint and input.
211 The first step is to configure a wrapper tag:
212
213 ```ruby
214 SimpleForm.wrapper_tag = :p
215 ```
216
217 And now, you don't need to wrap your f.input calls anymore:
218
219 ```erb
220 <%= simple_form_for @user do |f| %>
221 <%= f.input :username %>
222 <%= f.input :password %>
223 <%= f.button :submit %>
224 <% end %>
225 ```
226
227 ## Associations
228
229 To deal with associations, SimpleForm can generate select inputs, a series of radios or check boxes. Lets see how it works: imagine you have a user model that belongs to a company and has_and_belongs_to_many roles. The structure would be something like:
230
231 ```ruby
232 class User < ActiveRecord::Base
233 belongs_to :company
234 has_and_belongs_to_many :roles
235 end
236
237 class Company < ActiveRecord::Base
238 has_many :users
239 end
240
241 class Role < ActiveRecord::Base
242 has_and_belongs_to_many :users
243 end
244 ```
245
246 Now we have the user form:
247
248 ```erb
249 <%= simple_form_for @user do |f| %>
250 <%= f.input :name %>
251 <%= f.association :company %>
252 <%= f.association :roles %>
253 <%= f.button :submit %>
254 <% end %>
255 ```
256
257 Simple enough right? This is going to render a :select input for choosing the :company, and another :select input with :multiple option for the :roles. You can of course change it, to use radios and check boxes as well:
258
259 ```ruby
260 f.association :company, :as => :radio
261 f.association :roles, :as => :check_boxes
262 ```
263
264 The association helper just invokes input under the hood, so all options available to :select, :radio and :check_boxes are also available to association. Additionally, you can specify the collection by hand, all together with the prompt:
265
266 ```ruby
267 f.association :company, :collection => Company.active.all(:order => 'name'), :prompt => "Choose a Company"
268 ```
269
270 ## Buttons
271
272 All web forms need buttons, right? SimpleForm wraps them in the DSL, acting like a proxy:
273
274 ```erb
275 <%= simple_form_for @user do |f| %>
276 <%= f.input :name %>
277 <%= f.button :submit %>
278 <% end %>
279 ```
280
281 The above will simply call submit. You choose to use it or not, it's just a question of taste.
282
283 ## Wrapping Rails Form Helpers
284
285 Say you wanted to use a rails form helper but still wrap it in SimpleForm goodness? You can, by calling input with a block like so:
286
287 ```erb
288 <%= f.input :role do %>
289 <%= f.select :role, Role.all.map { |r| [r.name, r.id, { :class => r.company.id }] }, :include_blank => true %>
290 <% end %>
291 ```
292
293 In the above example, we're taking advantage of Rails 3's select method that allows us to pass in a hash of additional attributes for each option.
294
295 ## Extra helpers
296
297 SimpleForm also comes with some extra helpers you can use inside rails default forms without relying on simple_form_for helper. They are listed below.
298
299 ### Simple Fields For
300
301 Wrapper to use simple form inside a default rails form
302
303 ```ruby
304 form_for @user do |f|
305 f.simple_fields_for :posts do |posts_form|
306 # Here you have all simple_form methods available
307 posts_form.input :title
308 end
309 end
310 ```
311
312 ### Collection Radio
313
314 Creates a collection of radio inputs with labels associated (same API as collection_select):
315
316 ```ruby
317 form_for @user do |f|
318 f.collection_radio :options, [[true, 'Yes'] ,[false, 'No']], :first, :last
319 end
320 ```
321
322 ```html
323 <input id="user_options_true" name="user[options]" type="radio" value="true" />
324 <label class="collection_radio" for="user_options_true">Yes</label>
325 <input id="user_options_false" name="user[options]" type="radio" value="false" />
326 <label class="collection_radio" for="user_options_false">No</label>
327 ```
328
329 ### Collection Check Box
330
331 Creates a collection of check boxes with labels associated (same API as collection_select):
332
333 ```ruby
334 form_for @user do |f|
335 f.collection_check_boxes :options, [[true, 'Yes'] ,[false, 'No']], :first, :last
336 end
337 ```
338
339 ```html
340 <input name="user[options][]" type="hidden" value="" />
341 <input id="user_options_true" name="user[options][]" type="checkbox" value="true" />
342 <label class="collection_check_box" for="user_options_true">Yes</label>
343 <input name="user[options][]" type="hidden" value="" />
344 <input id="user_options_false" name="user[options][]" type="checkbox" value="false" />
345 <label class="collection_check_box" for="user_options_false">No</label>
346 ```
347
348 To use this with associations in your model, you can do the following:
349
350 ```ruby
351 form_for @user do |f|
352 f.collection_check_boxes :role_ids, Role.all, :id, :name # using :roles here is not going to work.
353 end
354 ```
355
356 ## Mappings/Inputs available
357
358 SimpleForm comes with a lot of default mappings:
359
6fcb98d @carlosantoniodasilva Fix Mappings/Inputs available table layout with md.
carlosantoniodasilva authored Sep 26, 2011
360 Mapping Input Column Type
361
362 boolean check box boolean
363 string text field string
364 email email field string with name matching "email"
365 url url field string with name matching "url"
366 tel tel field string with name matching "phone"
367 password password field string with name matching "password"
368 search search -
369 text text area text
370 file file field string, responding to file methods
371 hidden hidden field -
372 integer number field integer
373 float number field float
374 decimal number field decimal
375 range range field -
376 datetime datetime select datetime/timestamp
377 date date select date
378 time time select time
379 select collection select belongs_to/has_many/has_and_belongs_to_many associations
380 radio collection radio belongs_to
381 check_boxes collection check box has_many/has_and_belongs_to_many associations
382 country country select string with name matching "country"
383 time_zone time zone select string with name matching "time_zone"
61fc74b @olivierlacan Converted README to GitHub-flavored Markdown w/ syntax highlighting f…
olivierlacan authored Sep 23, 2011
384
385 ## Custom inputs
386
387 It is very easy to add custom inputs to SimpleForm. For instance, if you want to add a custom input that extends the string one, you just need to add this file:
388
389 ```ruby
390 # app/inputs/currency_input.rb
391 class CurrencyInput < SimpleForm::Inputs::Base
392 def input
393 "$ #{@builder.text_field(attribute_name, input_html_options)}".html_safe
394 end
395 end
396 ```
397
398 And use it in your views:
399
400 ```ruby
401 f.input :money, :as => :currency
402 ```
403
404 You can also redefine existing SimpleForm inputs by creating a new class with the same name. For instance, if you want to wrap date/time/datetime in a div, you can do:
405
406 ```ruby
407 # app/inputs/date_time_input.rb
408 class DateTimeInput < SimpleForm::Inputs::DateTimeInput
409 def input
410 "<div>#{super}</div>".html_safe
411 end
412 end
413 ```
414
415 ## Custom form builder
416
417 You can create a custom form builder that uses SimpleForm.
418
419 Create a helper method that calls simple_form_for with a custom builder:
420
421 ```ruby
422 def custom_form_for(object, *args, &block)
423 options = args.extract_options!
424 simple_form_for(object, *(args << options.merge(:builder => CustomFormBuilder)), &block)
425 end
426 ```
427
428 Create a form builder class that inherits from SimpleForm::FormBuilder.
429
430 ```ruby
431 class CustomFormBuilder < SimpleForm::FormBuilder
432 def input(attribute_name, options = {}, &block)
433 options[:input_html].merge! :class => 'custom'
434 super
435 end
436 end
437 ```
438
439 ## I18n
440
441 SimpleForm uses all power of I18n API to lookup labels, hints and placeholders. To customize your forms you can create a locale file like this:
442
443 ```yaml
444 en:
445 simple_form:
446 labels:
447 user:
448 username: 'User name'
449 password: 'Password'
450 hints:
451 user:
452 username: 'User name to sign in.'
453 password: 'No special characters, please.'
454 placeholders:
455 user:
456 username: 'Your username'
457 password: '****'
458 ```
459
460 And your forms will use this information to render the components for you.
461
462 SimpleForm also lets you be more specific, separating lookups through actions for labels, hints and placeholders. Let's say you want a different label for new and edit actions, the locale file would be something like:
463
464 ```yaml
465 en:
466 simple_form:
467 labels:
468 user:
469 username: 'User name'
470 password: 'Password'
471 edit:
472 username: 'Change user name'
473 password: 'Change password'
474 ```
475
476 This way SimpleForm will figure out the right translation for you, based on the action being rendered. And to be a little bit DRYer with your locale file, you can skip the model information inside it:
477
478 ```yaml
479 en:
480 simple_form:
481 labels:
482 username: 'User name'
483 password: 'Password'
484 hints:
485 username: 'User name to sign in.'
486 password: 'No special characters, please.'
487 placeholders:
488 username: 'Your username'
489 password: '****'
490 ```
491
492 SimpleForm will always look for a default attribute translation if no specific is found inside the model key. In addition, SimpleForm will fallback to default human_attribute_name from Rails when no other translation is found for labels.
493
494 Finally, you can also overwrite any label, hint or placeholder inside your view, just by passing the option manually. This way the I18n lookup will be skipped.
495
496 It's also possible to translate buttons, using Rails' built-in I18n support:
497
498 ```yaml
499 en:
500 helpers:
501 submit:
502 user:
503 create: "Add %{model}"
504 update: "Save Changes"
505 ```
506
507 There are other options that can be configured through I18n API, such as required text and boolean. Be sure to check our locale file or the one copied to your application after you run "rails generate simple_form:install".
508
509 ## HTML 5 Notice
510
511 By default, SimpleForm will generate input field types and attributes that are supported in HTML5, but are considered invalid HTML for older document types such as HTML4 or XHTML1.0. The HTML5 extensions include the new field types such as email, number, search, url, tel, and the new attributes such as required, autofocus, maxlength, min, max, step.
512
513 Most browsers will not care, but some of the newer ones - in particular Chrome 10+ - use the required attribute to force a value into an input and will prevent form submission without it. Depending on the design of the application this may or may not be desired. In many cases it can break existing UI's.
514
515 It is possible to disable all HTML 5 extensions in SimpleForm with the following configuration:
516
517 ```ruby
518 SimpleForm.html5 = false # default is true
519 ```
520
521 If you want to have all other HTML 5 features, such as the new field types, you can disable only the browser validation:
522
523 ```ruby
524 SimpleForm.browser_validations = false # default is true
525 ```
526
527 This option adds a new `novalidate` property to the form, instructing it to skip all HTML 5 validation. The inputs will still be generated with the required and other attributes, that might help you to use some generic javascript validation.
528
529 You can also add `novalidate` to a specific form by setting the option on the form itself:
530
531 ```erb
532 <%= simple_form_for(resource, :html => {:novalidate => true}) do |form| %>
533 ```
534
535 Please notice that any of the configurations above will disable the `placeholder` component, which is an HTML 5 feature. We believe most of the newest browsers are handling this attribute fine, and if they aren't, any plugin you use would take of using the placeholder attribute to do it. However, you can disable it if you want, by removing the placeholder component from the components list in SimpleForm configuration file.
536
537 ## Configuration
538
539 SimpleForm has several configuration values. You can read and change them in the initializer created by SimpleForm, so if you haven't executed the command below yet, please do:
540
541 `rails generate simple_form:install`
542
543 ## Maintainers
544
545 * Carlos Antonio da Silva (https://github.com/carlosantoniodasilva)
546 * Rafael Mendonça França (https://github.com/rafaelfranca)
547
548 ## License
549
550 MIT License. Copyright 2011 Plataforma Tecnologia. http://blog.plataformatec.com.br
Something went wrong with that request. Please try again.