aboutsummaryrefslogtreecommitdiffstats
path: root/railties/doc/guides/source/form_helpers.txt
blob: d09ad15a908641ca69f2f42fcde084d7195593b4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
Rails form helpers
==================
Mislav Marohnić <mislav.marohnic@gmail.com>

Forms in web applications are an essential interface for user input. However, form markup can quickly become tedious to write and maintain because of form control naming and their numerous attributes. Rails deals away with these complexities by providing view helpers for generating form markup. However, since they have different use-cases, developers are required to know all the differences between similar helper methods before putting them to use.

In this guide we will:

* Create search forms and similar kind of generic forms not representing any specific model in your application;
* Make model-centric forms for creation and editing of specific database records;
* Generate select boxes from multiple types of data;
* Learn what makes a file upload form different;
* Build complex, multi-model forms.

NOTE: This guide is not intended to be a complete documentation of available form helpers and their arguments. Please visit http://api.rubyonrails.org/[the Rails API documentation] for a complete reference.


Basic forms
-----------

The most basic form helper is `form_tag`.

----------------------------------------------------------------------------
<% form_tag do %>
  Form contents
<% end %>
----------------------------------------------------------------------------

When called without arguments like this, it creates a form element that has the current page for action attribute and "POST" as method (some line breaks added for readability):

.Sample rendering of `form_tag`
----------------------------------------------------------------------------
<form action="/home/index" method="post">
  <div style="margin:0;padding:0">
    <input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" />
  </div>
  Form contents
</form>
----------------------------------------------------------------------------

If you carefully observe this output, you can see that the helper generated something we didn't specify: a `div` element with a hidden input inside. This is a security feature of Rails called *cross-site request forgery protection* and form helpers generate it for every form which action isn't "GET" (provided that this security feature is enabled).

NOTE: Throughout this guide, this `div` with the hidden input will be stripped away to have clearer code samples.

Generic search form
~~~~~~~~~~~~~~~~~~~

Probably the most minimal form often seen on the web is a search form with a single text input for search terms. This form consists of:

1. a form element with "GET" method,
2. a label for the input,
3. a text input element, and
4. a submit element.

IMPORTANT: Always use "GET" as the method for search forms. Benefits are many: users are able to bookmark a specific search and get back to it; browsers cache results of "GET" requests, but not "POST"; and other.

To create that, we will use `form_tag`, `label_tag`, `text_field_tag` and `submit_tag`, respectively.

.A basic search form
----------------------------------------------------------------------------
<% form_tag(search_path, :method => "get") do %>
  <%= label_tag(:q, "Search for:") %>
  <%= text_field_tag(:q) %>
  <%= submit_tag("Search") %>
<% end %>
----------------------------------------------------------------------------

[TIP]
============================================================================
`search_path` can be a named route specified in "routes.rb":

----------------------------------------------------------------------------
map.search "search", :controller => "search"
----------------------------------------------------------------------------
============================================================================

The above view code will result in the following markup:

.Search form HTML
----------------------------------------------------------------------------
<form action="/search" method="get">
  <label for="q">Search for:</label>
  <input id="q" name="q" type="text" />
  <input name="commit" type="submit" value="Search" />
</form>
----------------------------------------------------------------------------

Besides `text_field_tag` and `submit_tag`, there is a similar helper for _every_ form control in HTML.

TIP: For every form input, an ID attribute is generated from its name ("q" in our example). These IDs can be very useful for CSS styling or manipulation of form controls with JavaScript.

Multiple hashes in form helper attributes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

By now we've seen that the `form_tag` helper accepts 2 arguments: the path for the action attribute and an options hash for parameters (like `:method`).

Identical to the `link_to` helper, the path argument doesn't have to be given as string or a named route. It can be a hash of URL parameters that Rails' routing mechanism will turn into a valid URL. Still, we cannot simply write this:

.A bad way to pass multiple hashes as method arguments
----------------------------------------------------------------------------
form_tag(:controller => "people", :action => "search", :method => "get")
# => <form action="/people/search?method=get" method="post">
----------------------------------------------------------------------------

Here we wanted to pass two hashes, but the Ruby interpreter sees only one hash, so Rails will construct a URL that we didn't want. The solution is to delimit the first hash (or both hashes) with curly brackets:

.The correct way of passing multiple hashes as arguments
----------------------------------------------------------------------------
form_tag({:controller => "people", :action => "search"}, :method => "get")
# => <form action="/people/search" method="get">
----------------------------------------------------------------------------

This is a common pitfall when using form helpers, since many of them accept multiple hashes. So in future, if a helper produces unexpected output, make sure that you have delimited the hash parameters properly.

WARNING: Do not delimit the second hash without doing so with the first hash, otherwise your method invocation will result in an `expecting tASSOC` syntax error.

Checkboxes, radio buttons and other controls
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Checkboxes are form controls that give the user a set of options they can enable or disable:

----------------------------------------------------------------------------
<%= check_box_tag(:pet_dog) %>
  <%= label_tag(:pet_dog, "I own a dog") %>
<%= check_box_tag(:pet_cat) %>
  <%= label_tag(:pet_cat, "I own a cat") %>

output:

<input id="pet_dog" name="pet_dog" type="checkbox" value="1" />
  <label for="pet_dog">I own a dog</label>
<input id="pet_cat" name="pet_cat" type="checkbox" value="1" />
  <label for="pet_cat">I own a cat</label>
----------------------------------------------------------------------------

Radio buttons, while similar to checkboxes, are controls that specify a set of options in which they are mutually exclusive (user can only pick one):

----------------------------------------------------------------------------
<%= radio_button_tag(:age, "child") %>
  <%= label_tag(:age_child, "I am younger than 21") %>
<%= radio_button_tag(:age, "adult") %>
  <%= label_tag(:age_adult, "I'm over 21") %>

output:

<input id="age_child" name="age" type="radio" value="child" />
  <label for="age_child">I am younger than 21</label>
<input id="age_adult" name="age" type="radio" value="adult" />
  <label for="age_adult">I'm over 21</label>
----------------------------------------------------------------------------

IMPORTANT: Always use labels for each checkbox and radio button. They associate text with a specific option and provide a larger clickable region.

Other form controls we might mention are the text area, password input and hidden input:

----------------------------------------------------------------------------
<%= text_area_tag(:message, "Hi, nice site", :size => "24x6") %>
<%= password_field_tag(:password) %>
<%= hidden_field_tag(:parent_id, "5") %>

output:

<textarea id="message" name="message" cols="24" rows="6">Hi, nice site</textarea>
<input id="password" name="password" type="password" />
<input id="parent_id" name="parent_id" type="hidden" value="5" />
----------------------------------------------------------------------------

Hidden inputs are not shown to the user, but they hold data same as any textual input. Values inside them can be changed with JavaScript.

TIP: If you're using password input fields (for any purpose), you might want to prevent their values showing up in application logs by activating `filter_parameter_logging(:password)` in your ApplicationController.

How do forms with PUT or DELETE methods work?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Rails framework encourages RESTful design of your applications, which means you'll be making a lot of "PUT" and "DELETE" requests (besides "GET" and "POST"). Still, most browsers _don't support_ methods other than "GET" and "POST" when it comes to submitting forms. How does this work, then?

Rails works around this issue by emulating other methods over POST with a hidden input named `"_method"` that is set to reflect the wanted method:

----------------------------------------------------------------------------
form_tag(search_path, :method => "put")
  
output:

<form action="/search" method="post">
  <div style="margin:0;padding:0">
    <input name="_method" type="hidden" value="put" />
    <input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" />
  </div>
  ...
----------------------------------------------------------------------------

When parsing POSTed data, Rails will take into account the special `"_method"` parameter and act as if the HTTP method was the one specified inside it ("PUT" in this example).


Forms that deal with model attributes
-------------------------------------

When we're dealing with an actual model, we will use a different set of form helpers and have Rails take care of some details in the background. In the following examples we will handle an Article model. First, let us have the controller create one:

.articles_controller.rb
----------------------------------------------------------------------------
def new
  @article = Article.new
end
----------------------------------------------------------------------------

Now we switch to the view. The first thing to remember is that we should use `form_for` helper instead of `form_tag`, and that we should pass the model name and object as arguments:

.articles/new.html.erb
----------------------------------------------------------------------------
<% form_for :article, @article, :url => { :action => "create" } do |f| %>
  <%= f.text_field :title %>
  <%= f.text_area :body, :size => "60x12" %>
  <%= submit_tag "Create" %>
<% end %>
----------------------------------------------------------------------------

There are a few things to note here:

1. `:article` is the name of the model and `@article` is our record.
2. The URL for the action attribute is passed as a parameter named `:url`.
3. The `form_for` method yields *a form builder* object (the `f` variable).
4. Methods to create form controls are called *on* the form builder object `f` and *without* the `"_tag"` suffix (so `text_field_tag` becomes `f.text_field`).

The resulting HTML is:

----------------------------------------------------------------------------
<form action="/articles/create" method="post">
  <input id="article_title" name="article[title]" size="30" type="text" />
  <textarea id="article_body" name="article[body]" cols="60" rows="12"></textarea>
  <input name="commit" type="submit" value="Create" />
</form>
----------------------------------------------------------------------------

A nice thing about `f.text_field` and other helper methods is that they will pre-fill the form control with the value read from the corresponding attribute in the model. For example, if we created the article instance by supplying an initial value for the title in the controller:

----------------------------------------------------------------------------
@article = Article.new(:title => "Rails makes forms easy")
----------------------------------------------------------------------------

... the corresponding input will be rendered with a value:

----------------------------------------------------------------------------
<input id="post_title" name="post[title]" size="30" type="text" value="Rails makes forms easy" />
----------------------------------------------------------------------------

Relying on record identification
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

In the previous chapter we handled the Article model. This model is directly available to users of our application, so -- following the best practices for developing with Rails -- we should declare it *a resource*.

When dealing with RESTful resources, our calls to `form_for` can get significantly easier if we rely on *record identification*. In short, we can just pass the model instance and have Rails figure out model name and the rest:

----------------------------------------------------------------------------
## Creating a new article
# long-style:
form_for(:article, @article, :url => articles_path)
# same thing, short-style (record identification gets used):
form_for(@article)

## Editing an existing article
# long-style:
form_for(:article, @article, :url => article_path(@article), :method => "put")
# short-style:
form_for(@article)
----------------------------------------------------------------------------

Notice how the short-style `form_for` invocation is conveniently the same, regardless of the record being new or existing. Record identification is smart enough to figure out if the record is new by asking `record.new_record?`.

WARNING: When you're using STI (single-table inheritance) with your models, you can't rely on record identification on a subclass if only their parent class is declared a resource. You will have to specify the model name, `:url` and `:method` explicitly.


Making select boxes with ease
-----------------------------

Select boxes in HTML require a significant amount of markup (one `OPTION` element for each option to choose from), therefore it makes the most sense for them to be dynamically generated from data stored in arrays or hashes.

Here is what our wanted markup might look like:

----------------------------------------------------------------------------
<select name="city_id" id="city_id">
  <option value="1">Lisabon</option>
  <option value="2">Madrid</option>
  ...
  <option value="12">Berlin</option>
</select>
----------------------------------------------------------------------------

Here we have a list of cities where their names are presented to the user, but internally we want to handle just their IDs so we keep them in value attributes. Let's see how Rails can help out here.

The select tag and options
~~~~~~~~~~~~~~~~~~~~~~~~~~

The most generic helper is `select_tag`, which -- as the name implies -- simply generates the `SELECT` tag that encapsulates an options string:

----------------------------------------------------------------------------
<%= select_tag(:city_id, '<option value="1">Lisabon</option>...') %>
----------------------------------------------------------------------------

This is a start, but it doesn't dynamically create our option tags. We can generate option tags with the `options_for_select` helper:

----------------------------------------------------------------------------
<%= options_for_select([['Lisabon', 1], ['Madrid', 2], ...]) %>

output:

<option value="1">Lisabon</option>
<option value="2">Madrid</option>
...
----------------------------------------------------------------------------

For input data we used a nested array where each item has two elements: option text (city name) and option value (city id).

Knowing this, you can combine `select_tag` and `options_for_select` to achieve the desired, complete markup:

----------------------------------------------------------------------------
<%= select_tag(:city_id, options_for_select(...)) %>
----------------------------------------------------------------------------

Sometimes, depending on our application's needs, we also wish a specific option to be pre-selected. The `options_for_select` helper supports this with an optional second argument:

----------------------------------------------------------------------------
<%= options_for_select(cities_array, 2) %>

output:

<option value="1">Lisabon</option>
<option value="2" selected="selected">Madrid</option>
...
----------------------------------------------------------------------------

So whenever Rails sees that the internal value of an option being generated matches this value, it will add the `selected` attribute to that option.

Select helpers for dealing with models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Until now we've covered how to make generic select boxes, but in most cases our form controls will be tied to a specific database model. So, to continue from our previous examples, let's assume that we have a "Person" model with a `city_id` attribute.

Consistent with other form helpers, when dealing with models we drop the `"_tag"` suffix from `select_tag` that we used in previous examples:

----------------------------------------------------------------------------
# controller:
@person = Person.new(:city_id => 2)

# view:
<%= select(:person, :city_id, [['Lisabon', 1], ['Madrid', 2], ...]) %>
----------------------------------------------------------------------------

Notice that the third parameter, the options array, is the same kind of argument we pass to `options_for_select`. One thing that we have as an advantage here is that we don't have to worry about pre-selecting the correct city if the user already has one -- Rails will do this for us by reading from `@person.city_id` attribute.

As before, if we were to use `select` helper on a form builder scoped to `@person` object, the syntax would be:

----------------------------------------------------------------------------
# select on a form builder
<%= f.select(:city_id, ...) %>
----------------------------------------------------------------------------

Option tags from a collection of arbitrary objects
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Until now we were generating option tags from nested arrays with the help of `options_for_select` method. Data in our array were raw values:

----------------------------------------------------------------------------
<%= options_for_select([['Lisabon', 1], ['Madrid', 2], ...]) %>
----------------------------------------------------------------------------

But what if we had a *City* model (perhaps an ActiveRecord one) and we wanted to generate option tags from a collection of those objects? One solution would be to make a nested array by iterating over them:

----------------------------------------------------------------------------
<% cities_array = City.find(:all).map { |city| [city.name, city.id] } %>
<%= options_for_select(cities_array) %>
----------------------------------------------------------------------------

This is a perfectly valid solution, but Rails provides us with a less verbose alternative: `options_from_collection_for_select`. This helper expects a collection of arbitrary objects and two additional arguments: the names of the methods to read the option *value* and *text* from, respectively:

----------------------------------------------------------------------------
<%= options_from_collection_for_select(City.all, :id, :name) %>
----------------------------------------------------------------------------

As the name implies, this only generates option tags. A method to go along with it is `collection_select`:

----------------------------------------------------------------------------
<%= collection_select(:person, :city_id, City.all, :id, :name) %>
----------------------------------------------------------------------------

To recap, `options_from_collection_for_select` are to `collection_select` what `options_for_select` are to `select`.

Time zone and country select
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

To leverage time zone support in Rails, we have to ask our users what time zone they are in. Doing so would require generating select options from a list of pre-defined TimeZone objects using `collection_select`, but we can simply use the `time_zone_select` helper that already wraps this:

----------------------------------------------------------------------------
<%= time_zone_select(:person, :city_id) %>
----------------------------------------------------------------------------

There is also `time_zone_options_for_select` helper for a more manual (therefore more customizable) way of doing this. Read the API documentation to learn about the possible arguments for these two methods.

When it comes to country select, Rails _used_ to have the built-in helper `country_select` but was extracted to a plugin.
TODO: plugin URL


Miscellaneous
-------------

File upload form
~~~~~~~~~~~~~~~~

:multipart - If set to true, the enctype is set to "multipart/form-data".

Scoping out form controls with `fields_for`
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Creates a scope around a specific model object like `form_for`, but doesn’t create the form tags themselves. This makes `fields_for` suitable for specifying additional model objects in the same form: 

Making custom form builders
~~~~~~~~~~~~~~~~~~~~~~~~~~~

You can also build forms using a customized FormBuilder class. Subclass FormBuilder and override or define some more helpers, then use your custom builder. For example, let’s say you made a helper to automatically add labels to form inputs.

----------------------------------------------------------------------------
<% form_for :person, @person, :url => { :action => "update" }, :builder => LabellingFormBuilder do |f| %>
  <%= f.text_field :first_name %>
  <%= f.text_field :last_name %>
  <%= text_area :person, :biography %>
  <%= check_box_tag "person[admin]", @person.company.admin? %>
<% end %>
----------------------------------------------------------------------------


* `form_for` within a namespace

----------------------------------------------------------------------------
select_tag(name, option_tags = nil, html_options = { :multiple, :disabled })

select(object, method, choices, options = {}, html_options = {})
options_for_select(container, selected = nil)

collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})
options_from_collection_for_select(collection, value_method, text_method, selected = nil)

time_zone_options_for_select(selected = nil, priority_zones = nil, model = ::ActiveSupport::TimeZone)
time_zone_select(object, method, priority_zones = nil, options = {}, html_options = {})
----------------------------------------------------------------------------