Froze rails gems
[depot.git] / vendor / rails / railties / doc / guides / source / form_helpers.txt
1 Rails form helpers
2 ==================
3 Mislav Marohnić <mislav.marohnic@gmail.com>
4
5 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.
6
7 In this guide we will:
8
9 * Create search forms and similar kind of generic forms not representing any specific model in your application;
10 * Make model-centric forms for creation and editing of specific database records;
11 * Generate select boxes from multiple types of data;
12 * Learn what makes a file upload form different;
13 * Build complex, multi-model forms.
14
15 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.
16
17
18 Basic forms
19 -----------
20
21 The most basic form helper is `form_tag`.
22
23 ----------------------------------------------------------------------------
24 <% form_tag do %>
25 Form contents
26 <% end %>
27 ----------------------------------------------------------------------------
28
29 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):
30
31 .Sample rendering of `form_tag`
32 ----------------------------------------------------------------------------
33 <form action="/home/index" method="post">
34 <div style="margin:0;padding:0">
35 <input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" />
36 </div>
37 Form contents
38 </form>
39 ----------------------------------------------------------------------------
40
41 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).
42
43 NOTE: Throughout this guide, this `div` with the hidden input will be stripped away to have clearer code samples.
44
45 Generic search form
46 ~~~~~~~~~~~~~~~~~~~
47
48 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:
49
50 1. a form element with "GET" method,
51 2. a label for the input,
52 3. a text input element, and
53 4. a submit element.
54
55 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.
56
57 To create that, we will use `form_tag`, `label_tag`, `text_field_tag` and `submit_tag`, respectively.
58
59 .A basic search form
60 ----------------------------------------------------------------------------
61 <% form_tag(search_path, :method => "get") do %>
62 <%= label_tag(:q, "Search for:") %>
63 <%= text_field_tag(:q) %>
64 <%= submit_tag("Search") %>
65 <% end %>
66 ----------------------------------------------------------------------------
67
68 [TIP]
69 ============================================================================
70 `search_path` can be a named route specified in "routes.rb":
71
72 ----------------------------------------------------------------------------
73 map.search "search", :controller => "search"
74 ----------------------------------------------------------------------------
75 ============================================================================
76
77 The above view code will result in the following markup:
78
79 .Search form HTML
80 ----------------------------------------------------------------------------
81 <form action="/search" method="get">
82 <label for="q">Search for:</label>
83 <input id="q" name="q" type="text" />
84 <input name="commit" type="submit" value="Search" />
85 </form>
86 ----------------------------------------------------------------------------
87
88 Besides `text_field_tag` and `submit_tag`, there is a similar helper for _every_ form control in HTML.
89
90 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.
91
92 Multiple hashes in form helper attributes
93 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
94
95 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`).
96
97 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:
98
99 .A bad way to pass multiple hashes as method arguments
100 ----------------------------------------------------------------------------
101 form_tag(:controller => "people", :action => "search", :method => "get")
102 # => <form action="/people/search?method=get" method="post">
103 ----------------------------------------------------------------------------
104
105 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:
106
107 .The correct way of passing multiple hashes as arguments
108 ----------------------------------------------------------------------------
109 form_tag({:controller => "people", :action => "search"}, :method => "get")
110 # => <form action="/people/search" method="get">
111 ----------------------------------------------------------------------------
112
113 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.
114
115 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.
116
117 Checkboxes, radio buttons and other controls
118 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
119
120 Checkboxes are form controls that give the user a set of options they can enable or disable:
121
122 ----------------------------------------------------------------------------
123 <%= check_box_tag(:pet_dog) %>
124 <%= label_tag(:pet_dog, "I own a dog") %>
125 <%= check_box_tag(:pet_cat) %>
126 <%= label_tag(:pet_cat, "I own a cat") %>
127
128 output:
129
130 <input id="pet_dog" name="pet_dog" type="checkbox" value="1" />
131 <label for="pet_dog">I own a dog</label>
132 <input id="pet_cat" name="pet_cat" type="checkbox" value="1" />
133 <label for="pet_cat">I own a cat</label>
134 ----------------------------------------------------------------------------
135
136 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):
137
138 ----------------------------------------------------------------------------
139 <%= radio_button_tag(:age, "child") %>
140 <%= label_tag(:age_child, "I am younger than 21") %>
141 <%= radio_button_tag(:age, "adult") %>
142 <%= label_tag(:age_adult, "I'm over 21") %>
143
144 output:
145
146 <input id="age_child" name="age" type="radio" value="child" />
147 <label for="age_child">I am younger than 21</label>
148 <input id="age_adult" name="age" type="radio" value="adult" />
149 <label for="age_adult">I'm over 21</label>
150 ----------------------------------------------------------------------------
151
152 IMPORTANT: Always use labels for each checkbox and radio button. They associate text with a specific option and provide a larger clickable region.
153
154 Other form controls we might mention are the text area, password input and hidden input:
155
156 ----------------------------------------------------------------------------
157 <%= text_area_tag(:message, "Hi, nice site", :size => "24x6") %>
158 <%= password_field_tag(:password) %>
159 <%= hidden_field_tag(:parent_id, "5") %>
160
161 output:
162
163 <textarea id="message" name="message" cols="24" rows="6">Hi, nice site</textarea>
164 <input id="password" name="password" type="password" />
165 <input id="parent_id" name="parent_id" type="hidden" value="5" />
166 ----------------------------------------------------------------------------
167
168 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.
169
170 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.
171
172 How do forms with PUT or DELETE methods work?
173 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
174
175 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?
176
177 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:
178
179 ----------------------------------------------------------------------------
180 form_tag(search_path, :method => "put")
181
182 output:
183
184 <form action="/search" method="post">
185 <div style="margin:0;padding:0">
186 <input name="_method" type="hidden" value="put" />
187 <input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" />
188 </div>
189 ...
190 ----------------------------------------------------------------------------
191
192 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).
193
194
195 Forms that deal with model attributes
196 -------------------------------------
197
198 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:
199
200 .articles_controller.rb
201 ----------------------------------------------------------------------------
202 def new
203 @article = Article.new
204 end
205 ----------------------------------------------------------------------------
206
207 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:
208
209 .articles/new.html.erb
210 ----------------------------------------------------------------------------
211 <% form_for :article, @article, :url => { :action => "create" } do |f| %>
212 <%= f.text_field :title %>
213 <%= f.text_area :body, :size => "60x12" %>
214 <%= submit_tag "Create" %>
215 <% end %>
216 ----------------------------------------------------------------------------
217
218 There are a few things to note here:
219
220 1. `:article` is the name of the model and `@article` is our record.
221 2. The URL for the action attribute is passed as a parameter named `:url`.
222 3. The `form_for` method yields *a form builder* object (the `f` variable).
223 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`).
224
225 The resulting HTML is:
226
227 ----------------------------------------------------------------------------
228 <form action="/articles/create" method="post">
229 <input id="article_title" name="article[title]" size="30" type="text" />
230 <textarea id="article_body" name="article[body]" cols="60" rows="12"></textarea>
231 <input name="commit" type="submit" value="Create" />
232 </form>
233 ----------------------------------------------------------------------------
234
235 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:
236
237 ----------------------------------------------------------------------------
238 @article = Article.new(:title => "Rails makes forms easy")
239 ----------------------------------------------------------------------------
240
241 ... the corresponding input will be rendered with a value:
242
243 ----------------------------------------------------------------------------
244 <input id="post_title" name="post[title]" size="30" type="text" value="Rails makes forms easy" />
245 ----------------------------------------------------------------------------
246
247 Relying on record identification
248 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
249
250 In the previous chapter we handled the Article model. This model is directly available to users of our application and, following the best practices for developing with Rails, we should declare it *a resource*.
251
252 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:
253
254 ----------------------------------------------------------------------------
255 ## Creating a new article
256 # long-style:
257 form_for(:article, @article, :url => articles_path)
258 # same thing, short-style (record identification gets used):
259 form_for(@article)
260
261 ## Editing an existing article
262 # long-style:
263 form_for(:article, @article, :url => article_path(@article), :method => "put")
264 # short-style:
265 form_for(@article)
266 ----------------------------------------------------------------------------
267
268 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?`.
269
270 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.
271
272
273 Making select boxes with ease
274 -----------------------------
275
276 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.
277
278 Here is what our wanted markup might look like:
279
280 ----------------------------------------------------------------------------
281 <select name="city_id" id="city_id">
282 <option value="1">Lisabon</option>
283 <option value="2">Madrid</option>
284 ...
285 <option value="12">Berlin</option>
286 </select>
287 ----------------------------------------------------------------------------
288
289 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.
290
291 The select tag and options
292 ~~~~~~~~~~~~~~~~~~~~~~~~~~
293
294 The most generic helper is `select_tag`, which -- as the name implies -- simply generates the `SELECT` tag that encapsulates the options:
295
296 ----------------------------------------------------------------------------
297 <%= select_tag(:city_id, '<option value="1">Lisabon</option>...') %>
298 ----------------------------------------------------------------------------
299
300 This is a start, but it doesn't dynamically create our option tags. We had to pass them in as a string.
301
302 We can generate option tags with the `options_for_select` helper:
303
304 ----------------------------------------------------------------------------
305 <%= options_for_select([['Lisabon', 1], ['Madrid', 2], ...]) %>
306
307 output:
308
309 <option value="1">Lisabon</option>
310 <option value="2">Madrid</option>
311 ...
312 ----------------------------------------------------------------------------
313
314 For input data we used a nested array where each element has two elements: visible value (name) and internal value (ID).
315
316 Now you can combine `select_tag` and `options_for_select` to achieve the desired, complete markup:
317
318 ----------------------------------------------------------------------------
319 <%= select_tag(:city_id, options_for_select(...)) %>
320 ----------------------------------------------------------------------------
321
322 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:
323
324 ----------------------------------------------------------------------------
325 <%= options_for_select(cities_array, 2) %>
326
327 output:
328
329 <option value="1">Lisabon</option>
330 <option value="2" selected="selected">Madrid</option>
331 ...
332 ----------------------------------------------------------------------------
333
334 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.
335
336 Select boxes for dealing with models
337 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
338
339 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.
340
341 ----------------------------------------------------------------------------
342 ...
343 ----------------------------------------------------------------------------
344
345 ...