PageRenderTime 58ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/External.LCA_RESTRICTED/Languages/Ruby/ruby19/lib/ruby/gems/1.9.1/gems/actionpack-3.0.0/lib/action_view/helpers/form_options_helper.rb

http://github.com/IronLanguages/main
Ruby | 627 lines | 190 code | 37 blank | 400 comment | 23 complexity | 7fc275a8e0ad341f7ca19f76b99879a6 MD5 | raw file
Possible License(s): CPL-1.0, BSD-3-Clause, ISC, GPL-2.0, MPL-2.0-no-copyleft-exception
  1. require 'cgi'
  2. require 'erb'
  3. require 'action_view/helpers/form_helper'
  4. require 'active_support/core_ext/object/blank'
  5. module ActionView
  6. # = Action View Form Option Helpers
  7. module Helpers
  8. # Provides a number of methods for turning different kinds of containers into a set of option tags.
  9. # == Options
  10. # The <tt>collection_select</tt>, <tt>select</tt> and <tt>time_zone_select</tt> methods take an <tt>options</tt> parameter, a hash:
  11. #
  12. # * <tt>:include_blank</tt> - set to true or a prompt string if the first option element of the select element is a blank. Useful if there is not a default value required for the select element.
  13. #
  14. # For example,
  15. #
  16. # select("post", "category", Post::CATEGORIES, {:include_blank => true})
  17. #
  18. # could become:
  19. #
  20. # <select name="post[category]">
  21. # <option></option>
  22. # <option>joke</option>
  23. # <option>poem</option>
  24. # </select>
  25. #
  26. # Another common case is a select tag for an <tt>belongs_to</tt>-associated object.
  27. #
  28. # Example with @post.person_id => 2:
  29. #
  30. # select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, {:include_blank => 'None'})
  31. #
  32. # could become:
  33. #
  34. # <select name="post[person_id]">
  35. # <option value="">None</option>
  36. # <option value="1">David</option>
  37. # <option value="2" selected="selected">Sam</option>
  38. # <option value="3">Tobias</option>
  39. # </select>
  40. #
  41. # * <tt>:prompt</tt> - set to true or a prompt string. When the select element doesn't have a value yet, this prepends an option with a generic prompt -- "Please select" -- or the given prompt string.
  42. #
  43. # Example:
  44. #
  45. # select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, {:prompt => 'Select Person'})
  46. #
  47. # could become:
  48. #
  49. # <select name="post[person_id]">
  50. # <option value="">Select Person</option>
  51. # <option value="1">David</option>
  52. # <option value="2">Sam</option>
  53. # <option value="3">Tobias</option>
  54. # </select>
  55. #
  56. # Like the other form helpers, +select+ can accept an <tt>:index</tt> option to manually set the ID used in the resulting output. Unlike other helpers, +select+ expects this
  57. # option to be in the +html_options+ parameter.
  58. #
  59. # Example:
  60. #
  61. # select("album[]", "genre", %w[rap rock country], {}, { :index => nil })
  62. #
  63. # becomes:
  64. #
  65. # <select name="album[][genre]" id="album__genre">
  66. # <option value="rap">rap</option>
  67. # <option value="rock">rock</option>
  68. # <option value="country">country</option>
  69. # </select>
  70. #
  71. # * <tt>:disabled</tt> - can be a single value or an array of values that will be disabled options in the final output.
  72. #
  73. # Example:
  74. #
  75. # select("post", "category", Post::CATEGORIES, {:disabled => 'restricted'})
  76. #
  77. # could become:
  78. #
  79. # <select name="post[category]">
  80. # <option></option>
  81. # <option>joke</option>
  82. # <option>poem</option>
  83. # <option disabled="disabled">restricted</option>
  84. # </select>
  85. #
  86. # When used with the <tt>collection_select</tt> helper, <tt>:disabled</tt> can also be a Proc that identifies those options that should be disabled.
  87. #
  88. # Example:
  89. #
  90. # collection_select(:post, :category_id, Category.all, :id, :name, {:disabled => lambda{|category| category.archived? }})
  91. #
  92. # If the categories "2008 stuff" and "Christmas" return true when the method <tt>archived?</tt> is called, this would return:
  93. # <select name="post[category_id]">
  94. # <option value="1" disabled="disabled">2008 stuff</option>
  95. # <option value="2" disabled="disabled">Christmas</option>
  96. # <option value="3">Jokes</option>
  97. # <option value="4">Poems</option>
  98. # </select>
  99. #
  100. module FormOptionsHelper
  101. # ERB::Util can mask some helpers like textilize. Make sure to include them.
  102. include ERB::Util
  103. include TextHelper
  104. # Create a select tag and a series of contained option tags for the provided object and method.
  105. # The option currently held by the object will be selected, provided that the object is available.
  106. # See options_for_select for the required format of the choices parameter.
  107. #
  108. # Example with @post.person_id => 1:
  109. # select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, { :include_blank => true })
  110. #
  111. # could become:
  112. #
  113. # <select name="post[person_id]">
  114. # <option value=""></option>
  115. # <option value="1" selected="selected">David</option>
  116. # <option value="2">Sam</option>
  117. # <option value="3">Tobias</option>
  118. # </select>
  119. #
  120. # This can be used to provide a default set of options in the standard way: before rendering the create form, a
  121. # new model instance is assigned the default options and bound to @model_name. Usually this model is not saved
  122. # to the database. Instead, a second model object is created when the create request is received.
  123. # This allows the user to submit a form page more than once with the expected results of creating multiple records.
  124. # In addition, this allows a single partial to be used to generate form inputs for both edit and create forms.
  125. #
  126. # By default, <tt>post.person_id</tt> is the selected option. Specify <tt>:selected => value</tt> to use a different selection
  127. # or <tt>:selected => nil</tt> to leave all options unselected. Similarly, you can specify values to be disabled in the option
  128. # tags by specifying the <tt>:disabled</tt> option. This can either be a single value or an array of values to be disabled.
  129. def select(object, method, choices, options = {}, html_options = {})
  130. InstanceTag.new(object, method, self, options.delete(:object)).to_select_tag(choices, options, html_options)
  131. end
  132. # Returns <tt><select></tt> and <tt><option></tt> tags for the collection of existing return values of
  133. # +method+ for +object+'s class. The value returned from calling +method+ on the instance +object+ will
  134. # be selected. If calling +method+ returns +nil+, no selection is made without including <tt>:prompt</tt>
  135. # or <tt>:include_blank</tt> in the +options+ hash.
  136. #
  137. # The <tt>:value_method</tt> and <tt>:text_method</tt> parameters are methods to be called on each member
  138. # of +collection+. The return values are used as the +value+ attribute and contents of each
  139. # <tt><option></tt> tag, respectively.
  140. #
  141. # Example object structure for use with this method:
  142. # class Post < ActiveRecord::Base
  143. # belongs_to :author
  144. # end
  145. # class Author < ActiveRecord::Base
  146. # has_many :posts
  147. # def name_with_initial
  148. # "#{first_name.first}. #{last_name}"
  149. # end
  150. # end
  151. #
  152. # Sample usage (selecting the associated Author for an instance of Post, <tt>@post</tt>):
  153. # collection_select(:post, :author_id, Author.all, :id, :name_with_initial, :prompt => true)
  154. #
  155. # If <tt>@post.author_id</tt> is already <tt>1</tt>, this would return:
  156. # <select name="post[author_id]">
  157. # <option value="">Please select</option>
  158. # <option value="1" selected="selected">D. Heinemeier Hansson</option>
  159. # <option value="2">D. Thomas</option>
  160. # <option value="3">M. Clark</option>
  161. # </select>
  162. def collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})
  163. InstanceTag.new(object, method, self, options.delete(:object)).to_collection_select_tag(collection, value_method, text_method, options, html_options)
  164. end
  165. # Returns <tt><select></tt>, <tt><optgroup></tt> and <tt><option></tt> tags for the collection of existing return values of
  166. # +method+ for +object+'s class. The value returned from calling +method+ on the instance +object+ will
  167. # be selected. If calling +method+ returns +nil+, no selection is made without including <tt>:prompt</tt>
  168. # or <tt>:include_blank</tt> in the +options+ hash.
  169. #
  170. # Parameters:
  171. # * +object+ - The instance of the class to be used for the select tag
  172. # * +method+ - The attribute of +object+ corresponding to the select tag
  173. # * +collection+ - An array of objects representing the <tt><optgroup></tt> tags.
  174. # * +group_method+ - The name of a method which, when called on a member of +collection+, returns an
  175. # array of child objects representing the <tt><option></tt> tags.
  176. # * +group_label_method+ - The name of a method which, when called on a member of +collection+, returns a
  177. # string to be used as the +label+ attribute for its <tt><optgroup></tt> tag.
  178. # * +option_key_method+ - The name of a method which, when called on a child object of a member of
  179. # +collection+, returns a value to be used as the +value+ attribute for its <tt><option></tt> tag.
  180. # * +option_value_method+ - The name of a method which, when called on a child object of a member of
  181. # +collection+, returns a value to be used as the contents of its <tt><option></tt> tag.
  182. #
  183. # Example object structure for use with this method:
  184. # class Continent < ActiveRecord::Base
  185. # has_many :countries
  186. # # attribs: id, name
  187. # end
  188. # class Country < ActiveRecord::Base
  189. # belongs_to :continent
  190. # # attribs: id, name, continent_id
  191. # end
  192. # class City < ActiveRecord::Base
  193. # belongs_to :country
  194. # # attribs: id, name, country_id
  195. # end
  196. #
  197. # Sample usage:
  198. # grouped_collection_select(:city, :country_id, @continents, :countries, :name, :id, :name)
  199. #
  200. # Possible output:
  201. # <select name="city[country_id]">
  202. # <optgroup label="Africa">
  203. # <option value="1">South Africa</option>
  204. # <option value="3">Somalia</option>
  205. # </optgroup>
  206. # <optgroup label="Europe">
  207. # <option value="7" selected="selected">Denmark</option>
  208. # <option value="2">Ireland</option>
  209. # </optgroup>
  210. # </select>
  211. #
  212. def grouped_collection_select(object, method, collection, group_method, group_label_method, option_key_method, option_value_method, options = {}, html_options = {})
  213. InstanceTag.new(object, method, self, options.delete(:object)).to_grouped_collection_select_tag(collection, group_method, group_label_method, option_key_method, option_value_method, options, html_options)
  214. end
  215. # Return select and option tags for the given object and method, using
  216. # #time_zone_options_for_select to generate the list of option tags.
  217. #
  218. # In addition to the <tt>:include_blank</tt> option documented above,
  219. # this method also supports a <tt>:model</tt> option, which defaults
  220. # to ActiveSupport::TimeZone. This may be used by users to specify a
  221. # different time zone model object. (See +time_zone_options_for_select+
  222. # for more information.)
  223. #
  224. # You can also supply an array of ActiveSupport::TimeZone objects
  225. # as +priority_zones+, so that they will be listed above the rest of the
  226. # (long) list. (You can use ActiveSupport::TimeZone.us_zones as a convenience
  227. # for obtaining a list of the US time zones, or a Regexp to select the zones
  228. # of your choice)
  229. #
  230. # Finally, this method supports a <tt>:default</tt> option, which selects
  231. # a default ActiveSupport::TimeZone if the object's time zone is +nil+.
  232. #
  233. # Examples:
  234. # time_zone_select( "user", "time_zone", nil, :include_blank => true)
  235. #
  236. # time_zone_select( "user", "time_zone", nil, :default => "Pacific Time (US & Canada)" )
  237. #
  238. # time_zone_select( "user", 'time_zone', ActiveSupport::TimeZone.us_zones, :default => "Pacific Time (US & Canada)")
  239. #
  240. # time_zone_select( "user", 'time_zone', [ ActiveSupport::TimeZone['Alaska'], ActiveSupport::TimeZone['Hawaii'] ])
  241. #
  242. # time_zone_select( "user", 'time_zone', /Australia/)
  243. #
  244. # time_zone_select( "user", "time_zone", ActiveSupport::Timezone.all.sort, :model => ActiveSupport::Timezone)
  245. def time_zone_select(object, method, priority_zones = nil, options = {}, html_options = {})
  246. InstanceTag.new(object, method, self, options.delete(:object)).to_time_zone_select_tag(priority_zones, options, html_options)
  247. end
  248. # Accepts a container (hash, array, enumerable, your type) and returns a string of option tags. Given a container
  249. # where the elements respond to first and last (such as a two-element array), the "lasts" serve as option values and
  250. # the "firsts" as option text. Hashes are turned into this form automatically, so the keys become "firsts" and values
  251. # become lasts. If +selected+ is specified, the matching "last" or element will get the selected option-tag. +selected+
  252. # may also be an array of values to be selected when using a multiple select.
  253. #
  254. # Examples (call, result):
  255. # options_for_select([["Dollar", "$"], ["Kroner", "DKK"]])
  256. # <option value="$">Dollar</option>\n<option value="DKK">Kroner</option>
  257. #
  258. # options_for_select([ "VISA", "MasterCard" ], "MasterCard")
  259. # <option>VISA</option>\n<option selected="selected">MasterCard</option>
  260. #
  261. # options_for_select({ "Basic" => "$20", "Plus" => "$40" }, "$40")
  262. # <option value="$20">Basic</option>\n<option value="$40" selected="selected">Plus</option>
  263. #
  264. # options_for_select([ "VISA", "MasterCard", "Discover" ], ["VISA", "Discover"])
  265. # <option selected="selected">VISA</option>\n<option>MasterCard</option>\n<option selected="selected">Discover</option>
  266. #
  267. # You can optionally provide html attributes as the last element of the array.
  268. #
  269. # Examples:
  270. # options_for_select([ "Denmark", ["USA", {:class=>'bold'}], "Sweden" ], ["USA", "Sweden"])
  271. # <option value="Denmark">Denmark</option>\n<option value="USA" class="bold" selected="selected">USA</option>\n<option value="Sweden" selected="selected">Sweden</option>
  272. #
  273. # options_for_select([["Dollar", "$", {:class=>"bold"}], ["Kroner", "DKK", {:onclick => "alert('HI');"}]])
  274. # <option value="$" class="bold">Dollar</option>\n<option value="DKK" onclick="alert('HI');">Kroner</option>
  275. #
  276. # If you wish to specify disabled option tags, set +selected+ to be a hash, with <tt>:disabled</tt> being either a value
  277. # or array of values to be disabled. In this case, you can use <tt>:selected</tt> to specify selected option tags.
  278. #
  279. # Examples:
  280. # options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], :disabled => "Super Platinum")
  281. # <option value="Free">Free</option>\n<option value="Basic">Basic</option>\n<option value="Advanced">Advanced</option>\n<option value="Super Platinum" disabled="disabled">Super Platinum</option>
  282. #
  283. # options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], :disabled => ["Advanced", "Super Platinum"])
  284. # <option value="Free">Free</option>\n<option value="Basic">Basic</option>\n<option value="Advanced" disabled="disabled">Advanced</option>\n<option value="Super Platinum" disabled="disabled">Super Platinum</option>
  285. #
  286. # options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], :selected => "Free", :disabled => "Super Platinum")
  287. # <option value="Free" selected="selected">Free</option>\n<option value="Basic">Basic</option>\n<option value="Advanced">Advanced</option>\n<option value="Super Platinum" disabled="disabled">Super Platinum</option>
  288. #
  289. # NOTE: Only the option tags are returned, you have to wrap this call in a regular HTML select tag.
  290. def options_for_select(container, selected = nil)
  291. return container if String === container
  292. container = container.to_a if Hash === container
  293. selected, disabled = extract_selected_and_disabled(selected).map do | r |
  294. Array.wrap(r).map(&:to_s)
  295. end
  296. container.map do |element|
  297. html_attributes = option_html_attributes(element)
  298. text, value = option_text_and_value(element).map(&:to_s)
  299. selected_attribute = ' selected="selected"' if option_value_selected?(value, selected)
  300. disabled_attribute = ' disabled="disabled"' if disabled && option_value_selected?(value, disabled)
  301. %(<option value="#{html_escape(value)}"#{selected_attribute}#{disabled_attribute}#{html_attributes}>#{html_escape(text)}</option>)
  302. end.join("\n").html_safe
  303. end
  304. # Returns a string of option tags that have been compiled by iterating over the +collection+ and assigning the
  305. # the result of a call to the +value_method+ as the option value and the +text_method+ as the option text.
  306. # Example:
  307. # options_from_collection_for_select(@people, 'id', 'name')
  308. # This will output the same HTML as if you did this:
  309. # <option value="#{person.id}">#{person.name}</option>
  310. #
  311. # This is more often than not used inside a #select_tag like this example:
  312. # select_tag 'person', options_from_collection_for_select(@people, 'id', 'name')
  313. #
  314. # If +selected+ is specified as a value or array of values, the element(s) returning a match on +value_method+
  315. # will be selected option tag(s).
  316. #
  317. # If +selected+ is specified as a Proc, those members of the collection that return true for the anonymous
  318. # function are the selected values.
  319. #
  320. # +selected+ can also be a hash, specifying both <tt>:selected</tt> and/or <tt>:disabled</tt> values as required.
  321. #
  322. # Be sure to specify the same class as the +value_method+ when specifying selected or disabled options.
  323. # Failure to do this will produce undesired results. Example:
  324. # options_from_collection_for_select(@people, 'id', 'name', '1')
  325. # Will not select a person with the id of 1 because 1 (an Integer) is not the same as '1' (a string)
  326. # options_from_collection_for_select(@people, 'id', 'name', 1)
  327. # should produce the desired results.
  328. def options_from_collection_for_select(collection, value_method, text_method, selected = nil)
  329. options = collection.map do |element|
  330. [element.send(text_method), element.send(value_method)]
  331. end
  332. selected, disabled = extract_selected_and_disabled(selected)
  333. select_deselect = {}
  334. select_deselect[:selected] = extract_values_from_collection(collection, value_method, selected)
  335. select_deselect[:disabled] = extract_values_from_collection(collection, value_method, disabled)
  336. options_for_select(options, select_deselect)
  337. end
  338. # Returns a string of <tt><option></tt> tags, like <tt>options_from_collection_for_select</tt>, but
  339. # groups them by <tt><optgroup></tt> tags based on the object relationships of the arguments.
  340. #
  341. # Parameters:
  342. # * +collection+ - An array of objects representing the <tt><optgroup></tt> tags.
  343. # * +group_method+ - The name of a method which, when called on a member of +collection+, returns an
  344. # array of child objects representing the <tt><option></tt> tags.
  345. # * group_label_method+ - The name of a method which, when called on a member of +collection+, returns a
  346. # string to be used as the +label+ attribute for its <tt><optgroup></tt> tag.
  347. # * +option_key_method+ - The name of a method which, when called on a child object of a member of
  348. # +collection+, returns a value to be used as the +value+ attribute for its <tt><option></tt> tag.
  349. # * +option_value_method+ - The name of a method which, when called on a child object of a member of
  350. # +collection+, returns a value to be used as the contents of its <tt><option></tt> tag.
  351. # * +selected_key+ - A value equal to the +value+ attribute for one of the <tt><option></tt> tags,
  352. # which will have the +selected+ attribute set. Corresponds to the return value of one of the calls
  353. # to +option_key_method+. If +nil+, no selection is made. Can also be a hash if disabled values are
  354. # to be specified.
  355. #
  356. # Example object structure for use with this method:
  357. # class Continent < ActiveRecord::Base
  358. # has_many :countries
  359. # # attribs: id, name
  360. # end
  361. # class Country < ActiveRecord::Base
  362. # belongs_to :continent
  363. # # attribs: id, name, continent_id
  364. # end
  365. #
  366. # Sample usage:
  367. # option_groups_from_collection_for_select(@continents, :countries, :name, :id, :name, 3)
  368. #
  369. # Possible output:
  370. # <optgroup label="Africa">
  371. # <option value="1">Egypt</option>
  372. # <option value="4">Rwanda</option>
  373. # ...
  374. # </optgroup>
  375. # <optgroup label="Asia">
  376. # <option value="3" selected="selected">China</option>
  377. # <option value="12">India</option>
  378. # <option value="5">Japan</option>
  379. # ...
  380. # </optgroup>
  381. #
  382. # <b>Note:</b> Only the <tt><optgroup></tt> and <tt><option></tt> tags are returned, so you still have to
  383. # wrap the output in an appropriate <tt><select></tt> tag.
  384. def option_groups_from_collection_for_select(collection, group_method, group_label_method, option_key_method, option_value_method, selected_key = nil)
  385. collection.inject("") do |options_for_select, group|
  386. group_label_string = eval("group.#{group_label_method}")
  387. options_for_select += "<optgroup label=\"#{html_escape(group_label_string)}\">"
  388. options_for_select += options_from_collection_for_select(eval("group.#{group_method}"), option_key_method, option_value_method, selected_key)
  389. options_for_select += '</optgroup>'
  390. end.html_safe
  391. end
  392. # Returns a string of <tt><option></tt> tags, like <tt>options_for_select</tt>, but
  393. # wraps them with <tt><optgroup></tt> tags.
  394. #
  395. # Parameters:
  396. # * +grouped_options+ - Accepts a nested array or hash of strings. The first value serves as the
  397. # <tt><optgroup></tt> label while the second value must be an array of options. The second value can be a
  398. # nested array of text-value pairs. See <tt>options_for_select</tt> for more info.
  399. # Ex. ["North America",[["United States","US"],["Canada","CA"]]]
  400. # * +selected_key+ - A value equal to the +value+ attribute for one of the <tt><option></tt> tags,
  401. # which will have the +selected+ attribute set. Note: It is possible for this value to match multiple options
  402. # as you might have the same option in multiple groups. Each will then get <tt>selected="selected"</tt>.
  403. # * +prompt+ - set to true or a prompt string. When the select element doesn't have a value yet, this
  404. # prepends an option with a generic prompt - "Please select" - or the given prompt string.
  405. #
  406. # Sample usage (Array):
  407. # grouped_options = [
  408. # ['North America',
  409. # [['United States','US'],'Canada']],
  410. # ['Europe',
  411. # ['Denmark','Germany','France']]
  412. # ]
  413. # grouped_options_for_select(grouped_options)
  414. #
  415. # Sample usage (Hash):
  416. # grouped_options = {
  417. # 'North America' => [['United States','US], 'Canada'],
  418. # 'Europe' => ['Denmark','Germany','France']
  419. # }
  420. # grouped_options_for_select(grouped_options)
  421. #
  422. # Possible output:
  423. # <optgroup label="Europe">
  424. # <option value="Denmark">Denmark</option>
  425. # <option value="Germany">Germany</option>
  426. # <option value="France">France</option>
  427. # </optgroup>
  428. # <optgroup label="North America">
  429. # <option value="US">United States</option>
  430. # <option value="Canada">Canada</option>
  431. # </optgroup>
  432. #
  433. # <b>Note:</b> Only the <tt><optgroup></tt> and <tt><option></tt> tags are returned, so you still have to
  434. # wrap the output in an appropriate <tt><select></tt> tag.
  435. def grouped_options_for_select(grouped_options, selected_key = nil, prompt = nil)
  436. body = ''
  437. body << content_tag(:option, prompt, { :value => "" }, true) if prompt
  438. grouped_options = grouped_options.sort if grouped_options.is_a?(Hash)
  439. grouped_options.each do |group|
  440. body << content_tag(:optgroup, options_for_select(group[1], selected_key), :label => group[0])
  441. end
  442. body.html_safe
  443. end
  444. # Returns a string of option tags for pretty much any time zone in the
  445. # world. Supply a ActiveSupport::TimeZone name as +selected+ to have it
  446. # marked as the selected option tag. You can also supply an array of
  447. # ActiveSupport::TimeZone objects as +priority_zones+, so that they will
  448. # be listed above the rest of the (long) list. (You can use
  449. # ActiveSupport::TimeZone.us_zones as a convenience for obtaining a list
  450. # of the US time zones, or a Regexp to select the zones of your choice)
  451. #
  452. # The +selected+ parameter must be either +nil+, or a string that names
  453. # a ActiveSupport::TimeZone.
  454. #
  455. # By default, +model+ is the ActiveSupport::TimeZone constant (which can
  456. # be obtained in Active Record as a value object). The only requirement
  457. # is that the +model+ parameter be an object that responds to +all+, and
  458. # returns an array of objects that represent time zones.
  459. #
  460. # NOTE: Only the option tags are returned, you have to wrap this call in
  461. # a regular HTML select tag.
  462. def time_zone_options_for_select(selected = nil, priority_zones = nil, model = ::ActiveSupport::TimeZone)
  463. zone_options = ""
  464. zones = model.all
  465. convert_zones = lambda { |list| list.map { |z| [ z.to_s, z.name ] } }
  466. if priority_zones
  467. if priority_zones.is_a?(Regexp)
  468. priority_zones = model.all.find_all {|z| z =~ priority_zones}
  469. end
  470. zone_options += options_for_select(convert_zones[priority_zones], selected)
  471. zone_options += "<option value=\"\" disabled=\"disabled\">-------------</option>\n"
  472. zones = zones.reject { |z| priority_zones.include?( z ) }
  473. end
  474. zone_options += options_for_select(convert_zones[zones], selected)
  475. zone_options.html_safe
  476. end
  477. private
  478. def option_html_attributes(element)
  479. return "" unless Array === element
  480. html_attributes = []
  481. element.select { |e| Hash === e }.reduce({}, :merge).each do |k, v|
  482. html_attributes << " #{k}=\"#{html_escape(v.to_s)}\""
  483. end
  484. html_attributes.join
  485. end
  486. def option_text_and_value(option)
  487. # Options are [text, value] pairs or strings used for both.
  488. case
  489. when Array === option
  490. option = option.reject { |e| Hash === e }
  491. [option.first, option.last]
  492. when !option.is_a?(String) && option.respond_to?(:first) && option.respond_to?(:last)
  493. [option.first, option.last]
  494. else
  495. [option, option]
  496. end
  497. end
  498. def option_value_selected?(value, selected)
  499. if selected.respond_to?(:include?) && !selected.is_a?(String)
  500. selected.include? value
  501. else
  502. value == selected
  503. end
  504. end
  505. def extract_selected_and_disabled(selected)
  506. if selected.is_a?(Proc)
  507. [ selected, nil ]
  508. else
  509. selected = Array.wrap(selected)
  510. options = selected.extract_options!.symbolize_keys
  511. [ options[:selected] || selected , options[:disabled] ]
  512. end
  513. end
  514. def extract_values_from_collection(collection, value_method, selected)
  515. if selected.is_a?(Proc)
  516. collection.map do |element|
  517. element.send(value_method) if selected.call(element)
  518. end.compact
  519. else
  520. selected
  521. end
  522. end
  523. end
  524. class InstanceTag #:nodoc:
  525. include FormOptionsHelper
  526. def to_select_tag(choices, options, html_options)
  527. html_options = html_options.stringify_keys
  528. add_default_name_and_id(html_options)
  529. value = value(object)
  530. selected_value = options.has_key?(:selected) ? options[:selected] : value
  531. disabled_value = options.has_key?(:disabled) ? options[:disabled] : nil
  532. content_tag("select", add_options(options_for_select(choices, :selected => selected_value, :disabled => disabled_value), options, selected_value), html_options)
  533. end
  534. def to_collection_select_tag(collection, value_method, text_method, options, html_options)
  535. html_options = html_options.stringify_keys
  536. add_default_name_and_id(html_options)
  537. value = value(object)
  538. disabled_value = options.has_key?(:disabled) ? options[:disabled] : nil
  539. selected_value = options.has_key?(:selected) ? options[:selected] : value
  540. content_tag(
  541. "select", add_options(options_from_collection_for_select(collection, value_method, text_method, :selected => selected_value, :disabled => disabled_value), options, value), html_options
  542. )
  543. end
  544. def to_grouped_collection_select_tag(collection, group_method, group_label_method, option_key_method, option_value_method, options, html_options)
  545. html_options = html_options.stringify_keys
  546. add_default_name_and_id(html_options)
  547. value = value(object)
  548. content_tag(
  549. "select", add_options(option_groups_from_collection_for_select(collection, group_method, group_label_method, option_key_method, option_value_method, value), options, value), html_options
  550. )
  551. end
  552. def to_time_zone_select_tag(priority_zones, options, html_options)
  553. html_options = html_options.stringify_keys
  554. add_default_name_and_id(html_options)
  555. value = value(object)
  556. content_tag("select",
  557. add_options(
  558. time_zone_options_for_select(value || options[:default], priority_zones, options[:model] || ActiveSupport::TimeZone),
  559. options, value
  560. ), html_options
  561. )
  562. end
  563. private
  564. def add_options(option_tags, options, value = nil)
  565. if options[:include_blank]
  566. option_tags = "<option value=\"\">#{html_escape(options[:include_blank]) if options[:include_blank].kind_of?(String)}</option>\n" + option_tags
  567. end
  568. if value.blank? && options[:prompt]
  569. prompt = options[:prompt].kind_of?(String) ? options[:prompt] : I18n.translate('helpers.select.prompt', :default => 'Please select')
  570. option_tags = "<option value=\"\">#{html_escape(prompt)}</option>\n" + option_tags
  571. end
  572. option_tags.html_safe
  573. end
  574. end
  575. class FormBuilder
  576. def select(method, choices, options = {}, html_options = {})
  577. @template.select(@object_name, method, choices, objectify_options(options), @default_options.merge(html_options))
  578. end
  579. def collection_select(method, collection, value_method, text_method, options = {}, html_options = {})
  580. @template.collection_select(@object_name, method, collection, value_method, text_method, objectify_options(options), @default_options.merge(html_options))
  581. end
  582. def grouped_collection_select(method, collection, group_method, group_label_method, option_key_method, option_value_method, options = {}, html_options = {})
  583. @template.grouped_collection_select(@object_name, method, collection, group_method, group_label_method, option_key_method, option_value_method, objectify_options(options), @default_options.merge(html_options))
  584. end
  585. def time_zone_select(method, priority_zones = nil, options = {}, html_options = {})
  586. @template.time_zone_select(@object_name, method, priority_zones, objectify_options(options), @default_options.merge(html_options))
  587. end
  588. end
  589. end
  590. end