Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 562 lines (411 sloc) 21.331 kb
5dd4a63b »
2011-11-08 Add travis-ci build image
1 # SimpleForm - Rails forms made easy.
2 [![Build Status](https://secure.travis-ci.org/plataformatec/simple_form.png)](http://travis-ci.org/plataformatec/simple_form)
61fc74bb »
2011-09-23 Converted README to GitHub-flavored Markdown w/ syntax highlighting f…
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
c04f7194 »
2011-11-09 Implements defaults options for simple_form_for.
100 If you want to pass the same :input_html to all inputs in the form (for example, a default class), you can use the :defaults option in `simple_form_for`. Specific options in :input_html will overwrite the defaults:
101
102 ```erb
103 <%= simple_form_for @user, :defaults => { :class => 'default_class' } do |f| %>
104 <%= f.input :username, :input_html => { :class => 'special' } %>
105 <%= f.input :password, :input_html => { :maxlength => 20 } %>
106 <%= f.input :remember_me, :input_html => { :value => '1' } %>
107 <%= f.button :submit %>
108 <% end %>
109 ```
110
8ee50d81 »
2011-09-28 Added :wrapper_html example to the README.
111 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:
112
113 ```erb
114 <%= simple_form_for @user do |f| %>
115 <%= f.input :username, :wrapper_html => { :class => 'username' } %>
116 <%= f.input :password, :wrapper_html => { :id => 'password' } %>
117 <%= f.input :remember_me, :wrapper_html => { :class => 'options' } %>
118 <%= f.button :submit %>
119 <% end %>
120 ```
121
61fc74bb »
2011-09-23 Converted README to GitHub-flavored Markdown w/ syntax highlighting f…
122 By default all inputs are required, which means an * is prepended to the label, but you can disable it in any input you want:
123
124 ```erb
125 <%= simple_form_for @user do |f| %>
126 <%= f.input :name, :required => false %>
127 <%= f.input :username %>
128 <%= f.input :password %>
129 <%= f.button :submit %>
130 <% end %>
131 ```
132
133 SimpleForm also lets you overwrite the default input type it creates:
134
135 ```erb
136 <%= simple_form_for @user do |f| %>
137 <%= f.input :username %>
138 <%= f.input :password %>
139 <%= f.input :description, :as => :text %>
140 <%= f.input :accepts, :as => :radio %>
141 <%= f.button :submit %>
142 <% end %>
143 ```
144
145 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.
146
147 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:
148
149 ```erb
150 <%= simple_form_for @user do |f| %>
151 <%= f.input :username, :disabled => true, :hint => "You cannot change your username." %>
152 <%= f.button :submit %>
153 <% end %>
154 ```
155
156 SimpleForm accepts same options as their corresponding input type helper in Rails:
157
158 ```erb
159 <%= simple_form_for @user do |f| %>
160 <%= f.input :date_of_birth, :as => :date, :start_year => Date.today.year - 90,
161 :end_year => Date.today.year - 12, :discard_day => true,
162 :order => [:month, :year] %>
163 <%= f.button :submit %>
164 <% end %>
165 ```
166
167 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):
168
169 ```erb
170 <%= simple_form_for @user do |f| %>
171 <%= f.label :username %>
172 <%= f.input_field :username %>
173 <%= f.hint 'No special characters, please!' %>
174 <%= f.error :username, :id => 'user_name_error' %>
175 <%= f.full_error :token %>
176 <%= f.submit 'Save' %>
177 <% end %>
178 ```
179
180 Any extra option passed to these methods will be rendered as html option.
181
182 ### Collections
183
184 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:
185
186 ```erb
187 <%= simple_form_for @user do |f| %>
188 <%= f.input :user %>
189 <%= f.input :age, :collection => 18..60 %>
190 <%= f.button :submit %>
191 <% end %>
192 ```
193
194 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).
195
196 Collection inputs accepts two other options beside collections:
197
198 * label_method => the label method to be applied to the collection to retrieve the label
199
200 * value_method => the value method to be applied to the collection to retrieve the value
201
202 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:
203
204 ```ruby
205 f.input :age, :collection => 18..60, :prompt => "Select your age"
206 ```
207
208 ### Priority
209
210 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:
211
212 ```ruby
213 f.input :residence_country, :priority => [ "Brazil" ]
214 f.input :time_zone, :priority => /US/
215 ```
216
217 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.
218
219 ### Wrapper
220
221 SimpleForm allows you to add a wrapper which contains the label, error, hint and input.
222 The first step is to configure a wrapper tag:
223
224 ```ruby
225 SimpleForm.wrapper_tag = :p
226 ```
227
228 And now, you don't need to wrap your f.input calls anymore:
229
230 ```erb
231 <%= simple_form_for @user do |f| %>
232 <%= f.input :username %>
233 <%= f.input :password %>
234 <%= f.button :submit %>
235 <% end %>
236 ```
237
238 ## Associations
239
240 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:
241
242 ```ruby
243 class User < ActiveRecord::Base
244 belongs_to :company
245 has_and_belongs_to_many :roles
246 end
247
248 class Company < ActiveRecord::Base
249 has_many :users
250 end
251
252 class Role < ActiveRecord::Base
253 has_and_belongs_to_many :users
254 end
255 ```
256
257 Now we have the user form:
258
259 ```erb
260 <%= simple_form_for @user do |f| %>
261 <%= f.input :name %>
262 <%= f.association :company %>
263 <%= f.association :roles %>
264 <%= f.button :submit %>
265 <% end %>
266 ```
267
268 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:
269
270 ```ruby
271 f.association :company, :as => :radio
272 f.association :roles, :as => :check_boxes
273 ```
274
275 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:
276
277 ```ruby
278 f.association :company, :collection => Company.active.all(:order => 'name'), :prompt => "Choose a Company"
279 ```
280
281 ## Buttons
282
283 All web forms need buttons, right? SimpleForm wraps them in the DSL, acting like a proxy:
284
285 ```erb
286 <%= simple_form_for @user do |f| %>
287 <%= f.input :name %>
288 <%= f.button :submit %>
289 <% end %>
290 ```
291
292 The above will simply call submit. You choose to use it or not, it's just a question of taste.
293
294 ## Wrapping Rails Form Helpers
295
296 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:
297
298 ```erb
299 <%= f.input :role do %>
300 <%= f.select :role, Role.all.map { |r| [r.name, r.id, { :class => r.company.id }] }, :include_blank => true %>
301 <% end %>
302 ```
303
304 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.
305
306 ## Extra helpers
307
308 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.
309
310 ### Simple Fields For
311
312 Wrapper to use simple form inside a default rails form
313
314 ```ruby
315 form_for @user do |f|
316 f.simple_fields_for :posts do |posts_form|
317 # Here you have all simple_form methods available
318 posts_form.input :title
319 end
320 end
321 ```
322
323 ### Collection Radio
324
325 Creates a collection of radio inputs with labels associated (same API as collection_select):
326
327 ```ruby
328 form_for @user do |f|
329 f.collection_radio :options, [[true, 'Yes'] ,[false, 'No']], :first, :last
330 end
331 ```
332
333 ```html
334 <input id="user_options_true" name="user[options]" type="radio" value="true" />
335 <label class="collection_radio" for="user_options_true">Yes</label>
336 <input id="user_options_false" name="user[options]" type="radio" value="false" />
337 <label class="collection_radio" for="user_options_false">No</label>
338 ```
339
340 ### Collection Check Box
341
342 Creates a collection of check boxes with labels associated (same API as collection_select):
343
344 ```ruby
345 form_for @user do |f|
346 f.collection_check_boxes :options, [[true, 'Yes'] ,[false, 'No']], :first, :last
347 end
348 ```
349
350 ```html
351 <input name="user[options][]" type="hidden" value="" />
352 <input id="user_options_true" name="user[options][]" type="checkbox" value="true" />
353 <label class="collection_check_box" for="user_options_true">Yes</label>
354 <input name="user[options][]" type="hidden" value="" />
355 <input id="user_options_false" name="user[options][]" type="checkbox" value="false" />
356 <label class="collection_check_box" for="user_options_false">No</label>
357 ```
358
359 To use this with associations in your model, you can do the following:
360
361 ```ruby
362 form_for @user do |f|
363 f.collection_check_boxes :role_ids, Role.all, :id, :name # using :roles here is not going to work.
364 end
365 ```
366
367 ## Mappings/Inputs available
368
369 SimpleForm comes with a lot of default mappings:
370
6fcb98dd »
2011-09-26 Fix Mappings/Inputs available table layout with md.
371 Mapping Input Column Type
372
373 boolean check box boolean
374 string text field string
375 email email field string with name matching "email"
376 url url field string with name matching "url"
377 tel tel field string with name matching "phone"
378 password password field string with name matching "password"
379 search search -
380 text text area text
381 file file field string, responding to file methods
382 hidden hidden field -
383 integer number field integer
384 float number field float
385 decimal number field decimal
386 range range field -
387 datetime datetime select datetime/timestamp
388 date date select date
389 time time select time
390 select collection select belongs_to/has_many/has_and_belongs_to_many associations
391 radio collection radio belongs_to
392 check_boxes collection check box has_many/has_and_belongs_to_many associations
393 country country select string with name matching "country"
394 time_zone time zone select string with name matching "time_zone"
61fc74bb »
2011-09-23 Converted README to GitHub-flavored Markdown w/ syntax highlighting f…
395
396 ## Custom inputs
397
398 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:
399
400 ```ruby
401 # app/inputs/currency_input.rb
402 class CurrencyInput < SimpleForm::Inputs::Base
403 def input
404 "$ #{@builder.text_field(attribute_name, input_html_options)}".html_safe
405 end
406 end
407 ```
408
409 And use it in your views:
410
411 ```ruby
412 f.input :money, :as => :currency
413 ```
414
415 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:
416
417 ```ruby
418 # app/inputs/date_time_input.rb
419 class DateTimeInput < SimpleForm::Inputs::DateTimeInput
420 def input
421 "<div>#{super}</div>".html_safe
422 end
423 end
424 ```
425
426 ## Custom form builder
427
428 You can create a custom form builder that uses SimpleForm.
429
430 Create a helper method that calls simple_form_for with a custom builder:
431
432 ```ruby
433 def custom_form_for(object, *args, &block)
434 options = args.extract_options!
435 simple_form_for(object, *(args << options.merge(:builder => CustomFormBuilder)), &block)
436 end
437 ```
438
439 Create a form builder class that inherits from SimpleForm::FormBuilder.
440
441 ```ruby
442 class CustomFormBuilder < SimpleForm::FormBuilder
443 def input(attribute_name, options = {}, &block)
444 options[:input_html].merge! :class => 'custom'
445 super
446 end
447 end
448 ```
449
450 ## I18n
451
452 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:
453
454 ```yaml
455 en:
456 simple_form:
457 labels:
458 user:
459 username: 'User name'
460 password: 'Password'
461 hints:
462 user:
463 username: 'User name to sign in.'
464 password: 'No special characters, please.'
465 placeholders:
466 user:
467 username: 'Your username'
468 password: '****'
469 ```
470
471 And your forms will use this information to render the components for you.
472
473 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:
474
475 ```yaml
476 en:
477 simple_form:
478 labels:
479 user:
480 username: 'User name'
481 password: 'Password'
482 edit:
483 username: 'Change user name'
484 password: 'Change password'
485 ```
486
487 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:
488
489 ```yaml
490 en:
491 simple_form:
492 labels:
493 username: 'User name'
494 password: 'Password'
495 hints:
496 username: 'User name to sign in.'
497 password: 'No special characters, please.'
498 placeholders:
499 username: 'Your username'
500 password: '****'
501 ```
502
503 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.
504
505 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.
506
507 It's also possible to translate buttons, using Rails' built-in I18n support:
508
509 ```yaml
510 en:
511 helpers:
512 submit:
513 user:
514 create: "Add %{model}"
515 update: "Save Changes"
516 ```
517
518 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".
519
520 ## HTML 5 Notice
521
522 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.
523
524 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.
525
526 It is possible to disable all HTML 5 extensions in SimpleForm with the following configuration:
527
528 ```ruby
529 SimpleForm.html5 = false # default is true
530 ```
531
532 If you want to have all other HTML 5 features, such as the new field types, you can disable only the browser validation:
533
534 ```ruby
535 SimpleForm.browser_validations = false # default is true
536 ```
537
538 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.
539
540 You can also add `novalidate` to a specific form by setting the option on the form itself:
541
542 ```erb
543 <%= simple_form_for(resource, :html => {:novalidate => true}) do |form| %>
544 ```
545
546 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.
547
548 ## Configuration
549
550 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:
551
552 `rails generate simple_form:install`
553
554 ## Maintainers
555
556 * Carlos Antonio da Silva (https://github.com/carlosantoniodasilva)
557 * Rafael Mendonça França (https://github.com/rafaelfranca)
558
559 ## License
560
c04f7194 »
2011-11-09 Implements defaults options for simple_form_for.
561 MIT License. Copyright 2011 Plataforma Tecnologia. http://blog.plataformatec.com.br
Something went wrong with that request. Please try again.