Froze rails gems
[depot.git] / vendor / rails / actionpack / lib / action_view / helpers / form_helper.rb
1 require 'cgi'
2 require 'action_view/helpers/date_helper'
3 require 'action_view/helpers/tag_helper'
4 require 'action_view/helpers/form_tag_helper'
5
6 module ActionView
7 module Helpers
8 # Form helpers are designed to make working with models much easier compared to using just standard HTML
9 # elements by providing a set of methods for creating forms based on your models. This helper generates the HTML
10 # for forms, providing a method for each sort of input (e.g., text, password, select, and so on). When the form
11 # is submitted (i.e., when the user hits the submit button or <tt>form.submit</tt> is called via JavaScript), the form inputs will be bundled into the <tt>params</tt> object and passed back to the controller.
12 #
13 # There are two types of form helpers: those that specifically work with model attributes and those that don't.
14 # This helper deals with those that work with model attributes; to see an example of form helpers that don't work
15 # with model attributes, check the ActionView::Helpers::FormTagHelper documentation.
16 #
17 # The core method of this helper, form_for, gives you the ability to create a form for a model instance;
18 # for example, let's say that you have a model <tt>Person</tt> and want to create a new instance of it:
19 #
20 # # Note: a @person variable will have been created in the controller.
21 # # For example: @person = Person.new
22 # <% form_for :person, @person, :url => { :action => "create" } do |f| %>
23 # <%= f.text_field :first_name %>
24 # <%= f.text_field :last_name %>
25 # <%= submit_tag 'Create' %>
26 # <% end %>
27 #
28 # The HTML generated for this would be:
29 #
30 # <form action="/persons/create" method="post">
31 # <input id="person_first_name" name="person[first_name]" size="30" type="text" />
32 # <input id="person_last_name" name="person[last_name]" size="30" type="text" />
33 # <input name="commit" type="submit" value="Create" />
34 # </form>
35 #
36 # If you are using a partial for your form fields, you can use this shortcut:
37 #
38 # <% form_for :person, @person, :url => { :action => "create" } do |f| %>
39 # <%= render :partial => f %>
40 # <%= submit_tag 'Create' %>
41 # <% end %>
42 #
43 # This example will render the <tt>people/_form</tt> partial, setting a local variable called <tt>form</tt> which references the yielded FormBuilder.
44 #
45 # The <tt>params</tt> object created when this form is submitted would look like:
46 #
47 # {"action"=>"create", "controller"=>"persons", "person"=>{"first_name"=>"William", "last_name"=>"Smith"}}
48 #
49 # The params hash has a nested <tt>person</tt> value, which can therefore be accessed with <tt>params[:person]</tt> in the controller.
50 # If were editing/updating an instance (e.g., <tt>Person.find(1)</tt> rather than <tt>Person.new</tt> in the controller), the objects
51 # attribute values are filled into the form (e.g., the <tt>person_first_name</tt> field would have that person's first name in it).
52 #
53 # If the object name contains square brackets the id for the object will be inserted. For example:
54 #
55 # <%= text_field "person[]", "name" %>
56 #
57 # ...will generate the following ERb.
58 #
59 # <input type="text" id="person_<%= @person.id %>_name" name="person[<%= @person.id %>][name]" value="<%= @person.name %>" />
60 #
61 # If the helper is being used to generate a repetitive sequence of similar form elements, for example in a partial
62 # used by <tt>render_collection_of_partials</tt>, the <tt>index</tt> option may come in handy. Example:
63 #
64 # <%= text_field "person", "name", "index" => 1 %>
65 #
66 # ...becomes...
67 #
68 # <input type="text" id="person_1_name" name="person[1][name]" value="<%= @person.name %>" />
69 #
70 # An <tt>index</tt> option may also be passed to <tt>form_for</tt> and <tt>fields_for</tt>. This automatically applies
71 # the <tt>index</tt> to all the nested fields.
72 #
73 # There are also methods for helping to build form tags in link:classes/ActionView/Helpers/FormOptionsHelper.html,
74 # link:classes/ActionView/Helpers/DateHelper.html, and link:classes/ActionView/Helpers/ActiveRecordHelper.html
75 module FormHelper
76 # Creates a form and a scope around a specific model object that is used as
77 # a base for questioning about values for the fields.
78 #
79 # Rails provides succinct resource-oriented form generation with +form_for+
80 # like this:
81 #
82 # <% form_for @offer do |f| %>
83 # <%= f.label :version, 'Version' %>:
84 # <%= f.text_field :version %><br />
85 # <%= f.label :author, 'Author' %>:
86 # <%= f.text_field :author %><br />
87 # <% end %>
88 #
89 # There, +form_for+ is able to generate the rest of RESTful form parameters
90 # based on introspection on the record, but to understand what it does we
91 # need to dig first into the alternative generic usage it is based upon.
92 #
93 # === Generic form_for
94 #
95 # The generic way to call +form_for+ yields a form builder around a model:
96 #
97 # <% form_for :person, :url => { :action => "update" } do |f| %>
98 # <%= f.error_messages %>
99 # First name: <%= f.text_field :first_name %><br />
100 # Last name : <%= f.text_field :last_name %><br />
101 # Biography : <%= f.text_area :biography %><br />
102 # Admin? : <%= f.check_box :admin %><br />
103 # <% end %>
104 #
105 # There, the first argument is a symbol or string with the name of the
106 # object the form is about, and also the name of the instance variable the
107 # object is stored in.
108 #
109 # The form builder acts as a regular form helper that somehow carries the
110 # model. Thus, the idea is that
111 #
112 # <%= f.text_field :first_name %>
113 #
114 # gets expanded to
115 #
116 # <%= text_field :person, :first_name %>
117 #
118 # If the instance variable is not <tt>@person</tt> you can pass the actual
119 # record as the second argument:
120 #
121 # <% form_for :person, person, :url => { :action => "update" } do |f| %>
122 # ...
123 # <% end %>
124 #
125 # In that case you can think
126 #
127 # <%= f.text_field :first_name %>
128 #
129 # gets expanded to
130 #
131 # <%= text_field :person, :first_name, :object => person %>
132 #
133 # You can even display error messages of the wrapped model this way:
134 #
135 # <%= f.error_messages %>
136 #
137 # In any of its variants, the rightmost argument to +form_for+ is an
138 # optional hash of options:
139 #
140 # * <tt>:url</tt> - The URL the form is submitted to. It takes the same fields
141 # you pass to +url_for+ or +link_to+. In particular you may pass here a
142 # named route directly as well. Defaults to the current action.
143 # * <tt>:html</tt> - Optional HTML attributes for the form tag.
144 #
145 # Worth noting is that the +form_for+ tag is called in a ERb evaluation block,
146 # not an ERb output block. So that's <tt><% %></tt>, not <tt><%= %></tt>.
147 #
148 # Also note that +form_for+ doesn't create an exclusive scope. It's still
149 # possible to use both the stand-alone FormHelper methods and methods from
150 # FormTagHelper. For example:
151 #
152 # <% form_for :person, @person, :url => { :action => "update" } do |f| %>
153 # First name: <%= f.text_field :first_name %>
154 # Last name : <%= f.text_field :last_name %>
155 # Biography : <%= text_area :person, :biography %>
156 # Admin? : <%= check_box_tag "person[admin]", @person.company.admin? %>
157 # <% end %>
158 #
159 # This also works for the methods in FormOptionHelper and DateHelper that are
160 # designed to work with an object as base, like FormOptionHelper#collection_select
161 # and DateHelper#datetime_select.
162 #
163 # === Resource-oriented style
164 #
165 # As we said above, in addition to manually configuring the +form_for+ call,
166 # you can rely on automated resource identification, which will use the conventions
167 # and named routes of that approach. This is the preferred way to use +form_for+
168 # nowadays.
169 #
170 # For example, if <tt>@post</tt> is an existing record you want to edit
171 #
172 # <% form_for @post do |f| %>
173 # ...
174 # <% end %>
175 #
176 # is equivalent to something like:
177 #
178 # <% form_for :post, @post, :url => post_path(@post), :html => { :method => :put, :class => "edit_post", :id => "edit_post_45" } do |f| %>
179 # ...
180 # <% end %>
181 #
182 # And for new records
183 #
184 # <% form_for(Post.new) do |f| %>
185 # ...
186 # <% end %>
187 #
188 # expands to
189 #
190 # <% form_for :post, Post.new, :url => posts_path, :html => { :class => "new_post", :id => "new_post" } do |f| %>
191 # ...
192 # <% end %>
193 #
194 # You can also overwrite the individual conventions, like this:
195 #
196 # <% form_for(@post, :url => super_post_path(@post)) do |f| %>
197 # ...
198 # <% end %>
199 #
200 # And for namespaced routes, like +admin_post_url+:
201 #
202 # <% form_for([:admin, @post]) do |f| %>
203 # ...
204 # <% end %>
205 #
206 # === Customized form builders
207 #
208 # You can also build forms using a customized FormBuilder class. Subclass FormBuilder and override or define some more helpers,
209 # then use your custom builder. For example, let's say you made a helper to automatically add labels to form inputs.
210 #
211 # <% form_for :person, @person, :url => { :action => "update" }, :builder => LabellingFormBuilder do |f| %>
212 # <%= f.text_field :first_name %>
213 # <%= f.text_field :last_name %>
214 # <%= text_area :person, :biography %>
215 # <%= check_box_tag "person[admin]", @person.company.admin? %>
216 # <% end %>
217 #
218 # In this case, if you use this:
219 #
220 # <%= render :partial => f %>
221 #
222 # The rendered template is <tt>people/_labelling_form</tt> and the local variable referencing the form builder is called <tt>labelling_form</tt>.
223 #
224 # In many cases you will want to wrap the above in another helper, so you could do something like the following:
225 #
226 # def labelled_form_for(record_or_name_or_array, *args, &proc)
227 # options = args.extract_options!
228 # form_for(record_or_name_or_array, *(args << options.merge(:builder => LabellingFormBuilder)), &proc)
229 # end
230 #
231 # If you don't need to attach a form to a model instance, then check out FormTagHelper#form_tag.
232 def form_for(record_or_name_or_array, *args, &proc)
233 raise ArgumentError, "Missing block" unless block_given?
234
235 options = args.extract_options!
236
237 case record_or_name_or_array
238 when String, Symbol
239 object_name = record_or_name_or_array
240 when Array
241 object = record_or_name_or_array.last
242 object_name = ActionController::RecordIdentifier.singular_class_name(object)
243 apply_form_for_options!(record_or_name_or_array, options)
244 args.unshift object
245 else
246 object = record_or_name_or_array
247 object_name = ActionController::RecordIdentifier.singular_class_name(object)
248 apply_form_for_options!([object], options)
249 args.unshift object
250 end
251
252 concat(form_tag(options.delete(:url) || {}, options.delete(:html) || {}))
253 fields_for(object_name, *(args << options), &proc)
254 concat('</form>')
255 end
256
257 def apply_form_for_options!(object_or_array, options) #:nodoc:
258 object = object_or_array.is_a?(Array) ? object_or_array.last : object_or_array
259
260 html_options =
261 if object.respond_to?(:new_record?) && object.new_record?
262 { :class => dom_class(object, :new), :id => dom_id(object), :method => :post }
263 else
264 { :class => dom_class(object, :edit), :id => dom_id(object, :edit), :method => :put }
265 end
266
267 options[:html] ||= {}
268 options[:html].reverse_merge!(html_options)
269 options[:url] ||= polymorphic_path(object_or_array)
270 end
271
272 # Creates a scope around a specific model object like form_for, but doesn't create the form tags themselves. This makes
273 # fields_for suitable for specifying additional model objects in the same form:
274 #
275 # ==== Examples
276 # <% form_for @person, :url => { :action => "update" } do |person_form| %>
277 # First name: <%= person_form.text_field :first_name %>
278 # Last name : <%= person_form.text_field :last_name %>
279 #
280 # <% fields_for @person.permission do |permission_fields| %>
281 # Admin? : <%= permission_fields.check_box :admin %>
282 # <% end %>
283 # <% end %>
284 #
285 # ...or if you have an object that needs to be represented as a different parameter, like a Client that acts as a Person:
286 #
287 # <% fields_for :person, @client do |permission_fields| %>
288 # Admin?: <%= permission_fields.check_box :admin %>
289 # <% end %>
290 #
291 # ...or if you don't have an object, just a name of the parameter
292 #
293 # <% fields_for :person do |permission_fields| %>
294 # Admin?: <%= permission_fields.check_box :admin %>
295 # <% end %>
296 #
297 # Note: This also works for the methods in FormOptionHelper and DateHelper that are designed to work with an object as base,
298 # like FormOptionHelper#collection_select and DateHelper#datetime_select.
299 def fields_for(record_or_name_or_array, *args, &block)
300 raise ArgumentError, "Missing block" unless block_given?
301 options = args.extract_options!
302
303 case record_or_name_or_array
304 when String, Symbol
305 object_name = record_or_name_or_array
306 object = args.first
307 else
308 object = record_or_name_or_array
309 object_name = ActionController::RecordIdentifier.singular_class_name(object)
310 end
311
312 builder = options[:builder] || ActionView::Base.default_form_builder
313 yield builder.new(object_name, object, self, options, block)
314 end
315
316 # Returns a label tag tailored for labelling an input field for a specified attribute (identified by +method+) on an object
317 # assigned to the template (identified by +object+). The text of label will default to the attribute name unless you specify
318 # it explicitly. Additional options on the label tag can be passed as a hash with +options+. These options will be tagged
319 # onto the HTML as an HTML element attribute as in the example shown.
320 #
321 # ==== Examples
322 # label(:post, :title)
323 # # => <label for="post_title">Title</label>
324 #
325 # label(:post, :title, "A short title")
326 # # => <label for="post_title">A short title</label>
327 #
328 # label(:post, :title, "A short title", :class => "title_label")
329 # # => <label for="post_title" class="title_label">A short title</label>
330 #
331 def label(object_name, method, text = nil, options = {})
332 InstanceTag.new(object_name, method, self, options.delete(:object)).to_label_tag(text, options)
333 end
334
335 # Returns an input tag of the "text" type tailored for accessing a specified attribute (identified by +method+) on an object
336 # assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
337 # hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example
338 # shown.
339 #
340 # ==== Examples
341 # text_field(:post, :title, :size => 20)
342 # # => <input type="text" id="post_title" name="post[title]" size="20" value="#{@post.title}" />
343 #
344 # text_field(:post, :title, :class => "create_input")
345 # # => <input type="text" id="post_title" name="post[title]" value="#{@post.title}" class="create_input" />
346 #
347 # text_field(:session, :user, :onchange => "if $('session[user]').value == 'admin' { alert('Your login can not be admin!'); }")
348 # # => <input type="text" id="session_user" name="session[user]" value="#{@session.user}" onchange = "if $('session[user]').value == 'admin' { alert('Your login can not be admin!'); }"/>
349 #
350 # text_field(:snippet, :code, :size => 20, :class => 'code_input')
351 # # => <input type="text" id="snippet_code" name="snippet[code]" size="20" value="#{@snippet.code}" class="code_input" />
352 #
353 def text_field(object_name, method, options = {})
354 InstanceTag.new(object_name, method, self, options.delete(:object)).to_input_field_tag("text", options)
355 end
356
357 # Returns an input tag of the "password" type tailored for accessing a specified attribute (identified by +method+) on an object
358 # assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
359 # hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example
360 # shown.
361 #
362 # ==== Examples
363 # password_field(:login, :pass, :size => 20)
364 # # => <input type="text" id="login_pass" name="login[pass]" size="20" value="#{@login.pass}" />
365 #
366 # password_field(:account, :secret, :class => "form_input")
367 # # => <input type="text" id="account_secret" name="account[secret]" value="#{@account.secret}" class="form_input" />
368 #
369 # password_field(:user, :password, :onchange => "if $('user[password]').length > 30 { alert('Your password needs to be shorter!'); }")
370 # # => <input type="text" id="user_password" name="user[password]" value="#{@user.password}" onchange = "if $('user[password]').length > 30 { alert('Your password needs to be shorter!'); }"/>
371 #
372 # password_field(:account, :pin, :size => 20, :class => 'form_input')
373 # # => <input type="text" id="account_pin" name="account[pin]" size="20" value="#{@account.pin}" class="form_input" />
374 #
375 def password_field(object_name, method, options = {})
376 InstanceTag.new(object_name, method, self, options.delete(:object)).to_input_field_tag("password", options)
377 end
378
379 # Returns a hidden input tag tailored for accessing a specified attribute (identified by +method+) on an object
380 # assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
381 # hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example
382 # shown.
383 #
384 # ==== Examples
385 # hidden_field(:signup, :pass_confirm)
386 # # => <input type="hidden" id="signup_pass_confirm" name="signup[pass_confirm]" value="#{@signup.pass_confirm}" />
387 #
388 # hidden_field(:post, :tag_list)
389 # # => <input type="hidden" id="post_tag_list" name="post[tag_list]" value="#{@post.tag_list}" />
390 #
391 # hidden_field(:user, :token)
392 # # => <input type="hidden" id="user_token" name="user[token]" value="#{@user.token}" />
393 def hidden_field(object_name, method, options = {})
394 InstanceTag.new(object_name, method, self, options.delete(:object)).to_input_field_tag("hidden", options)
395 end
396
397 # Returns an file upload input tag tailored for accessing a specified attribute (identified by +method+) on an object
398 # assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
399 # hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example
400 # shown.
401 #
402 # ==== Examples
403 # file_field(:user, :avatar)
404 # # => <input type="file" id="user_avatar" name="user[avatar]" />
405 #
406 # file_field(:post, :attached, :accept => 'text/html')
407 # # => <input type="file" id="post_attached" name="post[attached]" />
408 #
409 # file_field(:attachment, :file, :class => 'file_input')
410 # # => <input type="file" id="attachment_file" name="attachment[file]" class="file_input" />
411 #
412 def file_field(object_name, method, options = {})
413 InstanceTag.new(object_name, method, self, options.delete(:object)).to_input_field_tag("file", options)
414 end
415
416 # Returns a textarea opening and closing tag set tailored for accessing a specified attribute (identified by +method+)
417 # on an object assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
418 # hash with +options+.
419 #
420 # ==== Examples
421 # text_area(:post, :body, :cols => 20, :rows => 40)
422 # # => <textarea cols="20" rows="40" id="post_body" name="post[body]">
423 # # #{@post.body}
424 # # </textarea>
425 #
426 # text_area(:comment, :text, :size => "20x30")
427 # # => <textarea cols="20" rows="30" id="comment_text" name="comment[text]">
428 # # #{@comment.text}
429 # # </textarea>
430 #
431 # text_area(:application, :notes, :cols => 40, :rows => 15, :class => 'app_input')
432 # # => <textarea cols="40" rows="15" id="application_notes" name="application[notes]" class="app_input">
433 # # #{@application.notes}
434 # # </textarea>
435 #
436 # text_area(:entry, :body, :size => "20x20", :disabled => 'disabled')
437 # # => <textarea cols="20" rows="20" id="entry_body" name="entry[body]" disabled="disabled">
438 # # #{@entry.body}
439 # # </textarea>
440 def text_area(object_name, method, options = {})
441 InstanceTag.new(object_name, method, self, options.delete(:object)).to_text_area_tag(options)
442 end
443
444 # Returns a checkbox tag tailored for accessing a specified attribute (identified by +method+) on an object
445 # assigned to the template (identified by +object+). This object must be an instance object (@object) and not a local object.
446 # It's intended that +method+ returns an integer and if that integer is above zero, then the checkbox is checked.
447 # Additional options on the input tag can be passed as a hash with +options+. The +checked_value+ defaults to 1
448 # while the default +unchecked_value+ is set to 0 which is convenient for boolean values.
449 #
450 # ==== Gotcha
451 #
452 # The HTML specification says unchecked check boxes are not successful, and
453 # thus web browsers do not send them. Unfortunately this introduces a gotcha:
454 # if an Invoice model has a +paid+ flag, and in the form that edits a paid
455 # invoice the user unchecks its check box, no +paid+ parameter is sent. So,
456 # any mass-assignment idiom like
457 #
458 # @invoice.update_attributes(params[:invoice])
459 #
460 # wouldn't update the flag.
461 #
462 # To prevent this the helper generates a hidden field with the same name as
463 # the checkbox after the very check box. So, the client either sends only the
464 # hidden field (representing the check box is unchecked), or both fields.
465 # Since the HTML specification says key/value pairs have to be sent in the
466 # same order they appear in the form and Rails parameters extraction always
467 # gets the first occurrence of any given key, that works in ordinary forms.
468 #
469 # Unfortunately that workaround does not work when the check box goes
470 # within an array-like parameter, as in
471 #
472 # <% fields_for "project[invoice_attributes][]", invoice, :index => nil do |form| %>
473 # <%= form.check_box :paid %>
474 # ...
475 # <% end %>
476 #
477 # because parameter name repetition is precisely what Rails seeks to distinguish
478 # the elements of the array.
479 #
480 # ==== Examples
481 # # Let's say that @post.validated? is 1:
482 # check_box("post", "validated")
483 # # => <input type="checkbox" id="post_validated" name="post[validated]" value="1" />
484 # # <input name="post[validated]" type="hidden" value="0" />
485 #
486 # # Let's say that @puppy.gooddog is "no":
487 # check_box("puppy", "gooddog", {}, "yes", "no")
488 # # => <input type="checkbox" id="puppy_gooddog" name="puppy[gooddog]" value="yes" />
489 # # <input name="puppy[gooddog]" type="hidden" value="no" />
490 #
491 # check_box("eula", "accepted", { :class => 'eula_check' }, "yes", "no")
492 # # => <input type="checkbox" class="eula_check" id="eula_accepted" name="eula[accepted]" value="yes" />
493 # # <input name="eula[accepted]" type="hidden" value="no" />
494 #
495 def check_box(object_name, method, options = {}, checked_value = "1", unchecked_value = "0")
496 InstanceTag.new(object_name, method, self, options.delete(:object)).to_check_box_tag(options, checked_value, unchecked_value)
497 end
498
499 # Returns a radio button tag for accessing a specified attribute (identified by +method+) on an object
500 # assigned to the template (identified by +object+). If the current value of +method+ is +tag_value+ the
501 # radio button will be checked. Additional options on the input tag can be passed as a
502 # hash with +options+.
503 #
504 # ==== Examples
505 # # Let's say that @post.category returns "rails":
506 # radio_button("post", "category", "rails")
507 # radio_button("post", "category", "java")
508 # # => <input type="radio" id="post_category_rails" name="post[category]" value="rails" checked="checked" />
509 # # <input type="radio" id="post_category_java" name="post[category]" value="java" />
510 #
511 # radio_button("user", "receive_newsletter", "yes")
512 # radio_button("user", "receive_newsletter", "no")
513 # # => <input type="radio" id="user_receive_newsletter_yes" name="user[receive_newsletter]" value="yes" />
514 # # <input type="radio" id="user_receive_newsletter_no" name="user[receive_newsletter]" value="no" checked="checked" />
515 def radio_button(object_name, method, tag_value, options = {})
516 InstanceTag.new(object_name, method, self, options.delete(:object)).to_radio_button_tag(tag_value, options)
517 end
518 end
519
520 class InstanceTag #:nodoc:
521 include Helpers::TagHelper, Helpers::FormTagHelper
522
523 attr_reader :method_name, :object_name
524
525 DEFAULT_FIELD_OPTIONS = { "size" => 30 }.freeze unless const_defined?(:DEFAULT_FIELD_OPTIONS)
526 DEFAULT_RADIO_OPTIONS = { }.freeze unless const_defined?(:DEFAULT_RADIO_OPTIONS)
527 DEFAULT_TEXT_AREA_OPTIONS = { "cols" => 40, "rows" => 20 }.freeze unless const_defined?(:DEFAULT_TEXT_AREA_OPTIONS)
528
529 def initialize(object_name, method_name, template_object, object = nil)
530 @object_name, @method_name = object_name.to_s.dup, method_name.to_s.dup
531 @template_object = template_object
532 @object = object
533 if @object_name.sub!(/\[\]$/,"") || @object_name.sub!(/\[\]\]$/,"]")
534 if (object ||= @template_object.instance_variable_get("@#{Regexp.last_match.pre_match}")) && object.respond_to?(:to_param)
535 @auto_index = object.to_param
536 else
537 raise ArgumentError, "object[] naming but object param and @object var don't exist or don't respond to to_param: #{object.inspect}"
538 end
539 end
540 end
541
542 def to_label_tag(text = nil, options = {})
543 options = options.stringify_keys
544 name_and_id = options.dup
545 add_default_name_and_id(name_and_id)
546 options.delete("index")
547 options["for"] ||= name_and_id["id"]
548 content = (text.blank? ? nil : text.to_s) || method_name.humanize
549 label_tag(name_and_id["id"], content, options)
550 end
551
552 def to_input_field_tag(field_type, options = {})
553 options = options.stringify_keys
554 options["size"] = options["maxlength"] || DEFAULT_FIELD_OPTIONS["size"] unless options.key?("size")
555 options = DEFAULT_FIELD_OPTIONS.merge(options)
556 if field_type == "hidden"
557 options.delete("size")
558 end
559 options["type"] = field_type
560 options["value"] ||= value_before_type_cast(object) unless field_type == "file"
561 options["value"] &&= html_escape(options["value"])
562 add_default_name_and_id(options)
563 tag("input", options)
564 end
565
566 def to_radio_button_tag(tag_value, options = {})
567 options = DEFAULT_RADIO_OPTIONS.merge(options.stringify_keys)
568 options["type"] = "radio"
569 options["value"] = tag_value
570 if options.has_key?("checked")
571 cv = options.delete "checked"
572 checked = cv == true || cv == "checked"
573 else
574 checked = self.class.radio_button_checked?(value(object), tag_value)
575 end
576 options["checked"] = "checked" if checked
577 pretty_tag_value = tag_value.to_s.gsub(/\s/, "_").gsub(/\W/, "").downcase
578 options["id"] ||= defined?(@auto_index) ?
579 "#{tag_id_with_index(@auto_index)}_#{pretty_tag_value}" :
580 "#{tag_id}_#{pretty_tag_value}"
581 add_default_name_and_id(options)
582 tag("input", options)
583 end
584
585 def to_text_area_tag(options = {})
586 options = DEFAULT_TEXT_AREA_OPTIONS.merge(options.stringify_keys)
587 add_default_name_and_id(options)
588
589 if size = options.delete("size")
590 options["cols"], options["rows"] = size.split("x") if size.respond_to?(:split)
591 end
592
593 content_tag("textarea", html_escape(options.delete('value') || value_before_type_cast(object)), options)
594 end
595
596 def to_check_box_tag(options = {}, checked_value = "1", unchecked_value = "0")
597 options = options.stringify_keys
598 options["type"] = "checkbox"
599 options["value"] = checked_value
600 if options.has_key?("checked")
601 cv = options.delete "checked"
602 checked = cv == true || cv == "checked"
603 else
604 checked = self.class.check_box_checked?(value(object), checked_value)
605 end
606 options["checked"] = "checked" if checked
607 add_default_name_and_id(options)
608 tag("input", options) << tag("input", "name" => options["name"], "type" => "hidden", "value" => options['disabled'] && checked ? checked_value : unchecked_value)
609 end
610
611 def to_boolean_select_tag(options = {})
612 options = options.stringify_keys
613 add_default_name_and_id(options)
614 value = value(object)
615 tag_text = "<select"
616 tag_text << tag_options(options)
617 tag_text << "><option value=\"false\""
618 tag_text << " selected" if value == false
619 tag_text << ">False</option><option value=\"true\""
620 tag_text << " selected" if value
621 tag_text << ">True</option></select>"
622 end
623
624 def to_content_tag(tag_name, options = {})
625 content_tag(tag_name, value(object), options)
626 end
627
628 def object
629 @object || @template_object.instance_variable_get("@#{@object_name}")
630 rescue NameError
631 # As @object_name may contain the nested syntax (item[subobject]) we
632 # need to fallback to nil.
633 nil
634 end
635
636 def value(object)
637 self.class.value(object, @method_name)
638 end
639
640 def value_before_type_cast(object)
641 self.class.value_before_type_cast(object, @method_name)
642 end
643
644 class << self
645 def value(object, method_name)
646 object.send method_name unless object.nil?
647 end
648
649 def value_before_type_cast(object, method_name)
650 unless object.nil?
651 object.respond_to?(method_name + "_before_type_cast") ?
652 object.send(method_name + "_before_type_cast") :
653 object.send(method_name)
654 end
655 end
656
657 def check_box_checked?(value, checked_value)
658 case value
659 when TrueClass, FalseClass
660 value
661 when NilClass
662 false
663 when Integer
664 value != 0
665 when String
666 value == checked_value
667 when Array
668 value.include?(checked_value)
669 else
670 value.to_i != 0
671 end
672 end
673
674 def radio_button_checked?(value, checked_value)
675 value.to_s == checked_value.to_s
676 end
677 end
678
679 private
680 def add_default_name_and_id(options)
681 if options.has_key?("index")
682 options["name"] ||= tag_name_with_index(options["index"])
683 options["id"] ||= tag_id_with_index(options["index"])
684 options.delete("index")
685 elsif defined?(@auto_index)
686 options["name"] ||= tag_name_with_index(@auto_index)
687 options["id"] ||= tag_id_with_index(@auto_index)
688 else
689 options["name"] ||= tag_name + (options.has_key?('multiple') ? '[]' : '')
690 options["id"] ||= tag_id
691 end
692 end
693
694 def tag_name
695 "#{@object_name}[#{sanitized_method_name}]"
696 end
697
698 def tag_name_with_index(index)
699 "#{@object_name}[#{index}][#{sanitized_method_name}]"
700 end
701
702 def tag_id
703 "#{sanitized_object_name}_#{sanitized_method_name}"
704 end
705
706 def tag_id_with_index(index)
707 "#{sanitized_object_name}_#{index}_#{sanitized_method_name}"
708 end
709
710 def sanitized_object_name
711 @sanitized_object_name ||= @object_name.gsub(/\]\[|[^-a-zA-Z0-9:.]/, "_").sub(/_$/, "")
712 end
713
714 def sanitized_method_name
715 @sanitized_method_name ||= @method_name.sub(/\?$/,"")
716 end
717 end
718
719 class FormBuilder #:nodoc:
720 # The methods which wrap a form helper call.
721 class_inheritable_accessor :field_helpers
722 self.field_helpers = (FormHelper.instance_methods - ['form_for'])
723
724 attr_accessor :object_name, :object, :options
725
726 def initialize(object_name, object, template, options, proc)
727 @object_name, @object, @template, @options, @proc = object_name, object, template, options, proc
728 @default_options = @options ? @options.slice(:index) : {}
729 if @object_name.to_s.match(/\[\]$/)
730 if object ||= @template.instance_variable_get("@#{Regexp.last_match.pre_match}") and object.respond_to?(:to_param)
731 @auto_index = object.to_param
732 else
733 raise ArgumentError, "object[] naming but object param and @object var don't exist or don't respond to to_param: #{object.inspect}"
734 end
735 end
736 end
737
738 (field_helpers - %w(label check_box radio_button fields_for)).each do |selector|
739 src = <<-end_src
740 def #{selector}(method, options = {})
741 @template.send(#{selector.inspect}, @object_name, method, objectify_options(options))
742 end
743 end_src
744 class_eval src, __FILE__, __LINE__
745 end
746
747 def fields_for(record_or_name_or_array, *args, &block)
748 if options.has_key?(:index)
749 index = "[#{options[:index]}]"
750 elsif defined?(@auto_index)
751 self.object_name = @object_name.to_s.sub(/\[\]$/,"")
752 index = "[#{@auto_index}]"
753 else
754 index = ""
755 end
756
757 case record_or_name_or_array
758 when String, Symbol
759 name = "#{object_name}#{index}[#{record_or_name_or_array}]"
760 when Array
761 object = record_or_name_or_array.last
762 name = "#{object_name}#{index}[#{ActionController::RecordIdentifier.singular_class_name(object)}]"
763 args.unshift(object)
764 else
765 object = record_or_name_or_array
766 name = "#{object_name}#{index}[#{ActionController::RecordIdentifier.singular_class_name(object)}]"
767 args.unshift(object)
768 end
769
770 @template.fields_for(name, *args, &block)
771 end
772
773 def label(method, text = nil, options = {})
774 @template.label(@object_name, method, text, objectify_options(options))
775 end
776
777 def check_box(method, options = {}, checked_value = "1", unchecked_value = "0")
778 @template.check_box(@object_name, method, objectify_options(options), checked_value, unchecked_value)
779 end
780
781 def radio_button(method, tag_value, options = {})
782 @template.radio_button(@object_name, method, tag_value, objectify_options(options))
783 end
784
785 def error_message_on(method, *args)
786 @template.error_message_on(@object, method, *args)
787 end
788
789 def error_messages(options = {})
790 @template.error_messages_for(@object_name, objectify_options(options))
791 end
792
793 def submit(value = "Save changes", options = {})
794 @template.submit_tag(value, options.reverse_merge(:id => "#{object_name}_submit"))
795 end
796
797 private
798 def objectify_options(options)
799 @default_options.merge(options.merge(:object => @object))
800 end
801 end
802 end
803
804 class Base
805 cattr_accessor :default_form_builder
806 self.default_form_builder = ::ActionView::Helpers::FormBuilder
807 end
808 end