2 require 'action_view/helpers/date_helper'
3 require 'action_view/helpers/tag_helper'
4 require 'action_view/helpers/form_tag_helper'
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.
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.
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:
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' %>
28 # The HTML generated for this would be:
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" />
36 # If you are using a partial for your form fields, you can use this shortcut:
38 # <% form_for :person, @person, :url => { :action => "create" } do |f| %>
39 # <%= render :partial => f %>
40 # <%= submit_tag 'Create' %>
43 # This example will render the <tt>people/_form</tt> partial, setting a local variable called <tt>form</tt> which references the yielded FormBuilder.
45 # The <tt>params</tt> object created when this form is submitted would look like:
47 # {"action"=>"create", "controller"=>"persons", "person"=>{"first_name"=>"William", "last_name"=>"Smith"}}
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).
53 # If the object name contains square brackets the id for the object will be inserted. For example:
55 # <%= text_field "person[]", "name" %>
57 # ...will generate the following ERb.
59 # <input type="text" id="person_<%= @person.id %>_name" name="person[<%= @person.id %>][name]" value="<%= @person.name %>" />
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:
64 # <%= text_field "person", "name", "index" => 1 %>
68 # <input type="text" id="person_1_name" name="person[1][name]" value="<%= @person.name %>" />
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.
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
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.
79 # Rails provides succinct resource-oriented form generation with +form_for+
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 />
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.
93 # === Generic form_for
95 # The generic way to call +form_for+ yields a form builder around a model:
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 />
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.
109 # The form builder acts as a regular form helper that somehow carries the
110 # model. Thus, the idea is that
112 # <%= f.text_field :first_name %>
116 # <%= text_field :person, :first_name %>
118 # If the instance variable is not <tt>@person</tt> you can pass the actual
119 # record as the second argument:
121 # <% form_for :person, person, :url => { :action => "update" } do |f| %>
125 # In that case you can think
127 # <%= f.text_field :first_name %>
131 # <%= text_field :person, :first_name, :object => person %>
133 # You can even display error messages of the wrapped model this way:
135 # <%= f.error_messages %>
137 # In any of its variants, the rightmost argument to +form_for+ is an
138 # optional hash of options:
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.
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>.
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:
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? %>
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.
163 # === Resource-oriented style
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+
170 # For example, if <tt>@post</tt> is an existing record you want to edit
172 # <% form_for @post do |f| %>
176 # is equivalent to something like:
178 # <% form_for :post, @post, :url => post_path(@post), :html => { :method => :put, :class => "edit_post", :id => "edit_post_45" } do |f| %>
182 # And for new records
184 # <% form_for(Post.new) do |f| %>
190 # <% form_for :post, Post.new, :url => posts_path, :html => { :class => "new_post", :id => "new_post" } do |f| %>
194 # You can also overwrite the individual conventions, like this:
196 # <% form_for(@post, :url => super_post_path(@post)) do |f| %>
200 # And for namespaced routes, like +admin_post_url+:
202 # <% form_for([:admin, @post]) do |f| %>
206 # === Customized form builders
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.
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? %>
218 # In this case, if you use this:
220 # <%= render :partial => f %>
222 # The rendered template is <tt>people/_labelling_form</tt> and the local variable referencing the form builder is called <tt>labelling_form</tt>.
224 # In many cases you will want to wrap the above in another helper, so you could do something like the following:
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)
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
?
235 options
= args
.extract_options
!
237 case record_or_name_or_array
239 object_name
= record_or_name_or_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
)
246 object
= record_or_name_or_array
247 object_name
= ActionController
::RecordIdentifier.singular_class_name(object
)
248 apply_form_for_options
!([object
], options
)
252 concat(form_tag(options
.delete(:url) || {}, options
.delete(:html) || {}))
253 fields_for(object_name
, *(args
<< options
), &proc
)
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
261 if object
.respond_to
?(:new_record?) && object
.new_record
?
262 { :class => dom_class(object
, :new), :id => dom_id(object
), :method => :post }
264 { :class => dom_class(object
, :edit), :id => dom_id(object
, :edit), :method => :put }
267 options
[:html] ||= {}
268 options
[:html].reverse_merge
!(html_options
)
269 options
[:url] ||= polymorphic_path(object_or_array
)
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:
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 %>
280 # <% fields_for @person.permission do |permission_fields| %>
281 # Admin? : <%= permission_fields.check_box :admin %>
285 # ...or if you have an object that needs to be represented as a different parameter, like a Client that acts as a Person:
287 # <% fields_for :person, @client do |permission_fields| %>
288 # Admin?: <%= permission_fields.check_box :admin %>
291 # ...or if you don't have an object, just a name of the parameter
293 # <% fields_for :person do |permission_fields| %>
294 # Admin?: <%= permission_fields.check_box :admin %>
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
!
303 case record_or_name_or_array
305 object_name
= record_or_name_or_array
308 object
= record_or_name_or_array
309 object_name
= ActionController
::RecordIdentifier.singular_class_name(object
)
312 builder
= options
[:builder] || ActionView
::Base.default_form_builder
313 yield builder
.new(object_name
, object
, self, options
, block
)
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.
322 # label(:post, :title)
323 # # => <label for="post_title">Title</label>
325 # label(:post, :title, "A short title")
326 # # => <label for="post_title">A short title</label>
328 # label(:post, :title, "A short title", :class => "title_label")
329 # # => <label for="post_title" class="title_label">A short title</label>
331 def label(object_name
, method
, text
= nil, options
= {})
332 InstanceTag
.new(object_name
, method
, self, options
.delete(:object)).to_label_tag(text
, options
)
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
341 # text_field(:post, :title, :size => 20)
342 # # => <input type="text" id="post_title" name="post[title]" size="20" value="#{@post.title}" />
344 # text_field(:post, :title, :class => "create_input")
345 # # => <input type="text" id="post_title" name="post[title]" value="#{@post.title}" class="create_input" />
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!'); }"/>
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" />
353 def text_field(object_name
, method
, options
= {})
354 InstanceTag
.new(object_name
, method
, self, options
.delete(:object)).to_input_field_tag("text", options
)
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
363 # password_field(:login, :pass, :size => 20)
364 # # => <input type="text" id="login_pass" name="login[pass]" size="20" value="#{@login.pass}" />
366 # password_field(:account, :secret, :class => "form_input")
367 # # => <input type="text" id="account_secret" name="account[secret]" value="#{@account.secret}" class="form_input" />
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!'); }"/>
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" />
375 def password_field(object_name
, method
, options
= {})
376 InstanceTag
.new(object_name
, method
, self, options
.delete(:object)).to_input_field_tag("password", options
)
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
385 # hidden_field(:signup, :pass_confirm)
386 # # => <input type="hidden" id="signup_pass_confirm" name="signup[pass_confirm]" value="#{@signup.pass_confirm}" />
388 # hidden_field(:post, :tag_list)
389 # # => <input type="hidden" id="post_tag_list" name="post[tag_list]" value="#{@post.tag_list}" />
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
)
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
403 # file_field(:user, :avatar)
404 # # => <input type="file" id="user_avatar" name="user[avatar]" />
406 # file_field(:post, :attached, :accept => 'text/html')
407 # # => <input type="file" id="post_attached" name="post[attached]" />
409 # file_field(:attachment, :file, :class => 'file_input')
410 # # => <input type="file" id="attachment_file" name="attachment[file]" class="file_input" />
412 def file_field(object_name
, method
, options
= {})
413 InstanceTag
.new(object_name
, method
, self, options
.delete(:object)).to_input_field_tag("file", options
)
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+.
421 # text_area(:post, :body, :cols => 20, :rows => 40)
422 # # => <textarea cols="20" rows="40" id="post_body" name="post[body]">
426 # text_area(:comment, :text, :size => "20x30")
427 # # => <textarea cols="20" rows="30" id="comment_text" name="comment[text]">
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}
436 # text_area(:entry, :body, :size => "20x20", :disabled => 'disabled')
437 # # => <textarea cols="20" rows="20" id="entry_body" name="entry[body]" disabled="disabled">
440 def text_area(object_name
, method
, options
= {})
441 InstanceTag
.new(object_name
, method
, self, options
.delete(:object)).to_text_area_tag(options
)
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.
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
458 # @invoice.update_attributes(params[:invoice])
460 # wouldn't update the flag.
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.
469 # Unfortunately that workaround does not work when the check box goes
470 # within an array-like parameter, as in
472 # <% fields_for "project[invoice_attributes][]", invoice, :index => nil do |form| %>
473 # <%= form.check_box :paid %>
477 # because parameter name repetition is precisely what Rails seeks to distinguish
478 # the elements of the array.
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" />
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" />
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" />
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
)
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+.
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" />
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
)
520 class InstanceTag
#:nodoc:
521 include Helpers
::TagHelper, Helpers
::FormTagHelper
523 attr_reader
:method_name, :object_name
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)
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
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
537 raise ArgumentError
, "object[] naming but object param and @object var don't exist or don't respond to to_param: #{object.inspect}"
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
)
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")
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
)
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"
574 checked
= self.class.radio_button_checked
?(value(object
), tag_value
)
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
)
585 def to_text_area_tag(options
= {})
586 options
= DEFAULT_TEXT_AREA_OPTIONS
.merge(options
.stringify_keys
)
587 add_default_name_and_id(options
)
589 if size
= options
.delete("size")
590 options
["cols"], options
["rows"] = size
.split("x") if size
.respond_to
?(:split)
593 content_tag("textarea", html_escape(options
.delete('value') || value_before_type_cast(object
)), options
)
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"
604 checked
= self.class.check_box_checked
?(value(object
), checked_value
)
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
)
611 def to_boolean_select_tag(options
= {})
612 options
= options
.stringify_keys
613 add_default_name_and_id(options
)
614 value
= value(object
)
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>"
624 def to_content_tag(tag_name
, options
= {})
625 content_tag(tag_name
, value(object
), options
)
629 @object || @template_object.instance_variable_get("@#{@object_name}")
631 # As @object_name may contain the nested syntax (item[subobject]) we
632 # need to fallback to nil.
637 self.class.value(object
, @method_name)
640 def value_before_type_cast(object
)
641 self.class.value_before_type_cast(object
, @method_name)
645 def value(object
, method_name
)
646 object
.send method_name
unless object
.nil?
649 def value_before_type_cast(object
, method_name
)
651 object
.respond_to
?(method_name
+ "_before_type_cast") ?
652 object
.send(method_name
+ "_before_type_cast") :
653 object
.send(method_name
)
657 def check_box_checked
?(value
, checked_value
)
659 when TrueClass
, FalseClass
666 value
== checked_value
668 value
.include?(checked_value
)
674 def radio_button_checked
?(value
, checked_value
)
675 value
.to_s
== checked_value
.to_s
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)
689 options
["name"] ||= tag_name
+ (options
.has_key
?('multiple') ? '[]' : '')
690 options
["id"] ||= tag_id
695 "#{@object_name}[#{sanitized_method_name}]"
698 def tag_name_with_index(index
)
699 "#{@object_name}[#{index}][#{sanitized_method_name}]"
703 "#{sanitized_object_name}_#{sanitized_method_name}"
706 def tag_id_with_index(index
)
707 "#{sanitized_object_name}_#{index}_#{sanitized_method_name}"
710 def sanitized_object_name
711 @sanitized_object_name ||= @object_name.gsub(/\]\[|[^-a-zA-Z0-9:.]/, "_").sub(/_$/, "")
714 def sanitized_method_name
715 @sanitized_method_name ||= @method_name.sub(/\?$/,"")
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'])
724 attr_accessor
:object_name, :object, :options
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
733 raise ArgumentError
, "object[] naming but object param and @object var don't exist or don't respond to to_param: #{object.inspect}"
738 (field_helpers
- %w(label check_box radio_button fields_for
)).each
do |selector
|
740 def #{selector}(method, options = {})
741 @template.send(#{selector.inspect}, @object_name, method, objectify_options(options))
744 class_eval src
, __FILE__
, __LINE__
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}]"
757 case record_or_name_or_array
759 name
= "#{object_name}#{index}[#{record_or_name_or_array}]"
761 object
= record_or_name_or_array
.last
762 name
= "#{object_name}#{index}[#{ActionController::RecordIdentifier.singular_class_name(object)}]"
765 object
= record_or_name_or_array
766 name
= "#{object_name}#{index}[#{ActionController::RecordIdentifier.singular_class_name(object)}]"
770 @template.fields_for(name
, *args
, &block
)
773 def label(method
, text
= nil, options
= {})
774 @template.label(@object_name, method
, text
, objectify_options(options
))
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
)
781 def radio_button(method
, tag_value
, options
= {})
782 @template.radio_button(@object_name, method
, tag_value
, objectify_options(options
))
785 def error_message_on(method
, *args
)
786 @template.error_message_on(@object, method
, *args
)
789 def error_messages(options
= {})
790 @template.error_messages_for(@object_name, objectify_options(options
))
793 def submit(value
= "Save changes", options
= {})
794 @template.submit_tag(value
, options
.reverse_merge(:id => "#{object_name}_submit"))
798 def objectify_options(options
)
799 @default_options.merge(options
.merge(:object => @object))
805 cattr_accessor
:default_form_builder
806 self.default_form_builder
= ::ActionView::Helpers::FormBuilder