diff options
Diffstat (limited to 'railties')
-rw-r--r-- | railties/doc/guides/source/form_helpers.txt | 173 |
1 files changed, 92 insertions, 81 deletions
diff --git a/railties/doc/guides/source/form_helpers.txt b/railties/doc/guides/source/form_helpers.txt index 9cc434d938..0fd7c23c96 100644 --- a/railties/doc/guides/source/form_helpers.txt +++ b/railties/doc/guides/source/form_helpers.txt @@ -14,8 +14,8 @@ In this guide you will: 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 ------------ +Dealing With Basic Forms +------------------------ The most basic form helper is `form_tag`. @@ -113,9 +113,23 @@ This is a common pitfall when using form helpers, since many of them accept mult 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 -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Helpers for generating form elements +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Rails provides a series of helpers for generating form elements such as checkboxes, text fields, radio buttons and so. These basic helpers, with names ending in _tag such as `text_field_tag`, `check_box_tag` just generate a single `<input>` element. The first parameter to these is always the name of the input. This is the name under which value will appear in the `params` hash in the controller. For example if the form contains + +--------------------------- +<%= text_field_tag(:query) %> +--------------------------- +then the controller code should use +--------------------------- +params[:query] +--------------------------- +to retrieve the value entered by the user. When naming inputs be aware that Rails uses certain conventions that control whether values appear at the top level of the params hash, inside an array or a nested hash and so on. You can read more about them in the <<parameter_names,parameter names>> section. For details on the precise usage of these helpers, please refer to the http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html[API documentation]. + +Checkboxes +^^^^^^^^^^ Checkboxes are form controls that give the user a set of options they can enable or disable: ---------------------------------------------------------------------------- @@ -132,6 +146,10 @@ output: <label for="pet_cat">I own a cat</label> ---------------------------------------------------------------------------- +The second parameter to `check_box_tag` is the value of the input. This is the value that will be submitted by the browser if the checkbox is ticked (i.e. the value that will be present in the params hash). With the above form you would check the value of `params[:pet_dog]` and `params[:pet_cat]` to see which pets the user owns. + +Radio buttons +^^^^^^^^^^^^^ 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): ---------------------------------------------------------------------------- @@ -148,9 +166,13 @@ output: <label for="age_adult">I'm over 21</label> ---------------------------------------------------------------------------- +As with `check_box_tag` the second parameter to `radio_button_tag` is the value of the input. Because these two radio buttons share the same name (age) the user will only be able to select one and `params[:age]` will contain either `child` or `adult`. + 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 worth mentioning are the text area, password input and hidden input: +Other helpers of interest +^^^^^^^^^^^^^^^^^^^^^^^^^ +Other form controls worth mentioning are the text area, password input and hidden input: ---------------------------------------------------------------------------- <%= text_area_tag(:message, "Hi, nice site", :size => "24x6") %> @@ -164,55 +186,20 @@ output: <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. +Hidden inputs are not shown to the user, but they hold data like 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 desired 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). - -Different Families of helpers ------------------------------- - -Most of Rails' form helpers are available in two forms. - -Barebones helpers -~~~~~~~~~~~~~~~~~~ -These just generate the appropriate markup. These have names ending in _tag such as `text_field_tag`, `check_box_tag`. The first parameter to these is always the name of the input. This is the name under which value will appear in the `params` hash in the controller. For example if the form contains ---------------------------- -<%= text_field_tag(:query) %> ---------------------------- - -then the controller code should use ---------------------------- -params[:query] ---------------------------- -to retrieve the value entered by the user. When naming inputs be aware that Rails uses certain conventions that control whether values appear at the top level of the params hash, inside an array or a nested hash and so on. You can read more about them in the <<parameter_names,parameter names>> section. For details on the precise usage of these helpers, please refer to the http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html[API documentation]. +Dealing With Model Objects +-------------------------- Model object helpers -~~~~~~~~~~~~~~~~~~~~~ -These are designed to work with a model object (commonly an Active Record object but this need not be the case). These lack the _tag suffix, for example `text_field`, `text_area`. +~~~~~~~~~~~~~~~~~~~~~~ + +A particularly common task for a form is editing or creating a model object. While the `*_tag` helpers could certainly be used for this task they are somewhat verbose as for each tag you would have to ensure the correct parameter name is used and set the default value of the input appropriately. Rails provides helpers tailored to this task. These helpers lack the _tag suffix, for example `text_field`, `text_area`. -For these helpers the first arguement is the name of an instance variable and the second is the name a method (usually an attribute) to call on that object. Rails will set the value of the input control to the return value of that method for the object and set an appropriate input name. If your controller has defined `@person` and that person's name is Henry then a form containing: +For these helpers the first argument is the name of an instance variable and the second is the name of a method (usually an attribute) to call on that object. Rails will set the value of the input control to the return value of that method for the object and set an appropriate input name. If your controller has defined `@person` and that person's name is Henry then a form containing: --------------------------- <%= text_field(:person, :name) %> @@ -227,10 +214,13 @@ Upon form submission the value entered by the user will be stored in `params[:pe ============================================================================ You must pass the name of an instance variable, i.e. `:person` or `"person"`, not an actual instance of your model object. ============================================================================ -Forms that deal with model attributes -------------------------------------- -While the helpers seen so far are handy Rails can save you some work. For example typically a form is used to edit multiple attributes of a single object, so having to repeat the name of the object being edited is clumsy. The following examples will handle an Article model. First, have the controller create one: +Binding a form to an object +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +While this is an increase in comfort it is far from perfect. If Person has many attributes to edit then we would be repeating the name of the edited object many times. What we want to do is somehow bind a form to a model object which is exactly what `form_for` does. + +Assume we have a controller for dealing with articles: .articles_controller.rb ---------------------------------------------------------------------------- @@ -239,7 +229,7 @@ def new end ---------------------------------------------------------------------------- -Now switch to the view. The first thing to remember is to use the `form_for` helper instead of `form_tag`, and that you should pass the model name and object as arguments: +The corresponding view using `form_for` looks like this .articles/new.html.erb ---------------------------------------------------------------------------- @@ -252,9 +242,9 @@ Now switch to the view. The first thing to remember is to use the `form_for` hel There are a few things to note here: -1. `:article` is the name of the model and `@article` is the record. +1. `:article` is the name of the model and `@article` is the actual object being edited. 2. There is a single hash of options. Routing options are passed inside `:url` hash, HTML options are passed in the `:html` hash. -3. The `form_for` method yields *a form builder* object (the `f` variable). +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` The resulting HTML is: @@ -270,10 +260,30 @@ The name passed to `form_for` controls where in the params hash the form values The helper methods called on the form builder are identical to the model object helpers except that it is not necessary to specify which object is being edited since this is already managed by the form builder. +You can create a similar binding without actually creating `<form>` tags with the `fields_for` helper. This is useful for editing additional model objects with the same form. For example if you had a Person model with an associated ContactDetail model you could create a form for editing both like so: +------------- +<% form_for @person do |person_form| %> + <%= person_form.text_field :name %> + <% fields_for @person.contact_detail do |contact_details_form| %> + <%= contact_details_form.text_field :phone_number %> + <% end %> +<% end %> +------------- + +which produces the following output: + +------------- +<form action="/people/1" class="edit_person" id="edit_person_1" method="post"> + <input id="person_name" name="person[name]" size="30" type="text" /> + <input id="contact_detail_phone_number" name="contact_detail[phone_number]" size="30" type="text" /> +</form> +------------- +The object yielded by `fields_for` is a form builder like the one yielded by `form_for` (in fact `form_for` calls `fields_for` internally). + Relying on record identification ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -In the previous chapter you handled the Article model. This model is directly available to users of our application, so -- following the best practices for developing with Rails -- you should declare it *a resource*. +The Article model is directly available to users of our application, so -- following the best practices for developing with Rails -- you should declare it *a resource*. When dealing with RESTful resources, calls to `form_for` can get significantly easier if you rely on *record identification*. In short, you can just pass the model instance and have Rails figure out model name and the rest: @@ -312,6 +322,28 @@ form_for [:admin, :management, @article] For more information on Rails' routing system and the associated conventions, please see the link:../routing_outside_in.html[routing guide]. +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 desired 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). + + Making select boxes with ease ----------------------------- @@ -583,35 +615,14 @@ The form builder used also determines what happens when you do ------ If `f` is an instance of FormBuilder then this will render the 'form' partial, setting the partial's object to the form builder. If the form builder is of class LabellingFormBuilder then the 'labelling_form' partial would be rendered instead. -Scoping out form controls with `fields_for` -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -`fields_for` creates a form builder in exactly the same way as `form_for` but doesn't create the actual `<form>` tags. It creates a scope around a specific model object like `form_for`, which is useful for specifying additional model objects in the same form. For example if you had a Person model with an associated ContactDetail model you could create a form for editing both like so: -------------- -<% form_for @person do |person_form| %> - <%= person_form.text_field :name %> - <% fields_for @person.contact_detail do |contact_details_form| %> - <%= contact_details_form.text_field :phone_number %> - <% end %> -<% end %> -------------- - -which produces the following output: - -------------- -<form action="/people/1" class="edit_person" id="edit_person_1" method="post"> - <input id="person_name" name="person[name]" size="30" type="text" /> - <input id="contact_detail_phone_number" name="contact_detail[phone_number]" size="30" type="text" /> -</form> -------------- +Understanding Parameter Naming Conventions +----------------------------------------- -Parameter Names ---------------- [[parameter_names]] -As you've seen in the previous sections values from forms can appear either at the top level of the params hash or may appear nested in another hash. For example in a standard create +As you've seen in the previous sections, values from forms can appear either at the top level of the params hash or may appear nested in another hash. For example in a standard create action for a Person model, `params[:model]` would usually be a hash of all the attributes for the person to create. The params hash can also contain arrays, arrays of hashes and so on. -Fundamentally HTML forms don't know about any sort of structured data. All they know about is name-value pairs. Rails tacks some conventions onto parameter names which it uses to express some structure. +Fundamentally HTML forms don't know about any sort of structured data, all they generate is name-value pairs. The arrays and hashes you see in your application are the result of some parameter naming conventions that Rails uses. [TIP] ======================== @@ -724,8 +735,8 @@ As a shortcut you can append [] to the name and omit the `:index` option. This i -------- produces exactly the same output as the previous example. -Complex forms -------------- +Building Complex forms +---------------------- Many apps grow beyond simple forms editing a single object. For example when creating a Person instance you might want to allow the user to (on the same form) create multiple address records (home, work etc.). When later editing that person the user should be able to add, remove or amend addresses as necessary. While this guide has shown you all the pieces necessary to handle this, Rails does not yet have a standard end-to-end way of accomplishing this, but many have come up with viable approaches. These include: |