1 require 'action_view/helpers'
2 require 'active_support/i18n'
3 require 'active_support/core_ext/enumerable'
4 require 'active_support/core_ext/object/blank'
8 # The Active Record Helper makes it easier to create forms for records kept in instance variables. The most far-reaching is the +form+
9 # method that creates a complete form for all the basic content types of the record (not associations or aggregations, though). This
10 # is a great way of making the record quickly available for editing, but likely to prove lackluster for a complicated real-world form.
11 # In that case, it's better to use the +input+ method and the specialized +form+ methods in link:classes/ActionView/Helpers/FormHelper.html
13 # Returns a default input tag for the type of object returned by the method. For example, if <tt>@post</tt>
14 # has an attribute +title+ mapped to a +VARCHAR+ column that holds "Hello World":
16 # input("post", "title")
17 # # => <input id="post_title" name="post[title]" size="30" type="text" value="Hello World" />
18 def input(record_name, method, options = {})
19 InstanceTag.new(record_name, method, self).to_tag(options)
22 # Returns an entire form with all needed input tags for a specified Active Record object. For example, if <tt>@post</tt>
23 # has attributes named +title+ of type +VARCHAR+ and +body+ of type +TEXT+ then
27 # would yield a form like the following (modulus formatting):
29 # <form action='/posts/create' method='post'>
31 # <label for="post_title">Title</label><br />
32 # <input id="post_title" name="post[title]" size="30" type="text" value="Hello World" />
35 # <label for="post_body">Body</label><br />
36 # <textarea cols="40" id="post_body" name="post[body]" rows="20"></textarea>
38 # <input name="commit" type="submit" value="Create" />
41 # It's possible to specialize the form builder by using a different action name and by supplying another
42 # block renderer. For example, if <tt>@entry</tt> has an attribute +message+ of type +VARCHAR+ then
46 # :input_block => Proc.new { |record, column|
47 # "#{column.human_name}: #{input(record, column.name)}<br />"
50 # would yield a form like the following (modulus formatting):
52 # <form action="/entries/sign" method="post">
54 # <input id="entry_message" name="entry[message]" size="30" type="text" /><br />
55 # <input name="commit" type="submit" value="Sign" />
58 # It's also possible to add additional content to the form by giving it a block, such as:
60 # form("entry", :action => "sign") do |form|
61 # form << content_tag("b", "Department")
62 # form << collection_select("department", "id", @departments, "id", "name")
65 # The following options are available:
67 # * <tt>:action</tt> - The action used when submitting the form (default: +create+ if a new record, otherwise +update+).
68 # * <tt>:input_block</tt> - Specialize the output using a different block, see above.
69 # * <tt>:method</tt> - The method used when submitting the form (default: +post+).
70 # * <tt>:multipart</tt> - Whether to change the enctype of the form to "multipart/form-data", used when uploading a file (default: +false+).
71 # * <tt>:submit_value</tt> - The text of the submit button (default: "Create" if a new record, otherwise "Update").
72 def form(record_name, options = {})
73 record = instance_variable_get("@#{record_name}")
74 record = convert_to_model(record)
76 options = options.symbolize_keys
77 options[:action] ||= record.persisted? ? "update" : "create"
78 action = url_for(:action => options[:action], :id => record)
80 submit_value = options[:submit_value] || options[:action].gsub(/[^\w]/, '').capitalize
82 contents = form_tag({:action => action}, :method =>(options[:method] || 'post'), :enctype => options[:multipart] ? 'multipart/form-data': nil)
83 contents.safe_concat hidden_field(record_name, :id) if record.persisted?
84 contents.safe_concat all_input_tags(record, record_name, options)
85 yield contents if block_given?
86 contents.safe_concat submit_tag(submit_value)
87 contents.safe_concat('</form>')
90 # Returns a string containing the error message attached to the +method+ on the +object+ if one exists.
91 # This error message is wrapped in a <tt>DIV</tt> tag by default or with <tt>:html_tag</tt> if specified,
92 # which can be extended to include a <tt>:prepend_text</tt> and/or <tt>:append_text</tt> (to properly explain
93 # the error), and a <tt>:css_class</tt> to style it accordingly. +object+ should either be the name of an
94 # instance variable or the actual object. The method can be passed in either as a string or a symbol.
95 # As an example, let's say you have a model <tt>@post</tt> that has an error message on the +title+ attribute:
97 # <%= error_message_on "post", "title" %>
98 # # => <div class="formError">can't be empty</div>
100 # <%= error_message_on @post, :title %>
101 # # => <div class="formError">can't be empty</div>
103 # <%= error_message_on "post", "title",
104 # :prepend_text => "Title simply ",
105 # :append_text => " (or it won't work).",
106 # :html_tag => "span",
107 # :css_class => "inputError" %>
108 # # => <span class="inputError">Title simply can't be empty (or it won't work).</span>
109 def error_message_on(object, method, *args)
110 options = args.extract_options!
112 ActiveSupport::Deprecation.warn('error_message_on takes an option hash instead of separate ' +
113 'prepend_text, append_text, html_tag, and css_class arguments', caller)
115 options[:prepend_text] = args[0] || ''
116 options[:append_text] = args[1] || ''
117 options[:html_tag] = args[2] || 'div'
118 options[:css_class] = args[3] || 'formError'
120 options.reverse_merge!(:prepend_text => '', :append_text => '', :html_tag => 'div', :css_class => 'formError')
122 object = convert_to_model(object)
124 if (obj = (object.respond_to?(:errors) ? object : instance_variable_get("@#{object}"))) &&
125 (errors = obj.errors[method]).presence
126 content_tag(options[:html_tag],
127 (options[:prepend_text].html_safe << errors.first).safe_concat(options[:append_text]),
128 :class => options[:css_class]
135 # Returns a string with a <tt>DIV</tt> containing all of the error messages for the objects located as instance variables by the names
136 # given. If more than one object is specified, the errors for the objects are displayed in the order that the object names are
139 # This <tt>DIV</tt> can be tailored by the following options:
141 # * <tt>:header_tag</tt> - Used for the header of the error div (default: "h2").
142 # * <tt>:id</tt> - The id of the error div (default: "errorExplanation").
143 # * <tt>:class</tt> - The class of the error div (default: "errorExplanation").
144 # * <tt>:object</tt> - The object (or array of objects) for which to display errors,
145 # if you need to escape the instance variable convention.
146 # * <tt>:object_name</tt> - The object name to use in the header, or any text that you prefer.
147 # If <tt>:object_name</tt> is not set, the name of the first object will be used.
148 # * <tt>:header_message</tt> - The message in the header of the error div. Pass +nil+
149 # or an empty string to avoid the header message altogether. (Default: "X errors
150 # prohibited this object from being saved").
151 # * <tt>:message</tt> - The explanation message after the header message and before
152 # the error list. Pass +nil+ or an empty string to avoid the explanation message
153 # altogether. (Default: "There were problems with the following fields:").
155 # To specify the display for one object, you simply provide its name as a parameter.
156 # For example, for the <tt>@user</tt> model:
158 # error_messages_for 'user'
160 # You can also supply an object:
162 # error_messages_for @user
164 # This will use the last part of the model name in the presentation. For instance, if
165 # this is a MyKlass::User object, this will use "user" as the name in the String. This
166 # is taken from MyKlass::User.model_name.human, which can be overridden.
168 # To specify more than one object, you simply list them; optionally, you can add an extra <tt>:object_name</tt> parameter, which
169 # will be the name used in the header message:
171 # error_messages_for 'user_common', 'user', :object_name => 'user'
173 # You can also use a number of objects, which will have the same naming semantics
174 # as a single object.
176 # error_messages_for @user, @post
178 # If the objects cannot be located as instance variables, you can add an extra <tt>:object</tt> parameter which gives the actual
179 # object (or array of objects to use):
181 # error_messages_for 'user', :object => @question.user
183 # NOTE: This is a pre-packaged presentation of the errors with embedded strings and a certain HTML structure. If what
184 # you need is significantly different from the default presentation, it makes plenty of sense to access the <tt>object.errors</tt>
185 # instance yourself and set it up. View the source of this method to see how easy it is.
186 def error_messages_for(*params)
187 options = params.extract_options!.symbolize_keys
189 objects = Array.wrap(options.delete(:object) || params).map do |object|
190 object = instance_variable_get("@#{object}") unless object.respond_to?(:to_model)
191 object = convert_to_model(object)
193 if object.class.respond_to?(:model_name)
194 options[:object_name] ||= object.class.model_name.human.downcase
201 count = objects.inject(0) {|sum, object| sum + object.errors.count }
205 [:id, :class].each do |key|
206 if options.include?(key)
208 html[key] = value unless value.blank?
210 html[key] = 'errorExplanation'
213 options[:object_name] ||= params.first
215 I18n.with_options :locale => options[:locale], :scope => [:errors, :template] do |locale|
216 header_message = if options.include?(:header_message)
217 options[:header_message]
219 locale.t :header, :count => count, :model => options[:object_name].to_s.gsub('_', ' ')
222 message = options.include?(:message) ? options[:message] : locale.t(:body)
224 error_messages = objects.sum do |object|
225 object.errors.full_messages.map do |msg|
226 content_tag(:li, msg)
231 contents << content_tag(options[:header_tag] || :h2, header_message) unless header_message.blank?
232 contents << content_tag(:p, message) unless message.blank?
233 contents << content_tag(:ul, error_messages)
235 content_tag(:div, contents.html_safe, html)
244 def all_input_tags(record, record_name, options)
245 input_block = options[:input_block] || default_input_block
246 record.class.content_columns.collect{ |column| input_block.call(record_name, column) }.join("\n")
249 def default_input_block
250 Proc.new { |record, column| %(<p><label for="#{record}_#{column.name}">#{column.human_name}</label><br />#{input(record, column.name)}</p>) }
253 module InstanceTagMethods
254 def to_tag(options = {})
257 field_type = @method_name.include?("password") ? "password" : "text"
258 to_input_field_tag(field_type, options)
260 to_text_area_tag(options)
261 when :integer, :float, :decimal
262 to_input_field_tag("text", options)
264 to_date_select_tag(options)
265 when :datetime, :timestamp
266 to_datetime_select_tag(options)
268 to_time_select_tag(options)
270 to_boolean_select_tag(options)
275 object.send(:column_for_attribute, @method_name).type
279 module FormBuilderMethods
280 def error_message_on(method, *args)
281 @template.error_message_on(@object || @object_name, method, *args)
284 def error_messages(options = {})
285 @template.error_messages_for(@object_name, objectify_options(options))
291 include DynamicForm::InstanceTagMethods
295 include DynamicForm::FormBuilderMethods
300 I18n.load_path << File.expand_path("../../locale/en.yml", __FILE__)