Class: SimpleFormWithClientValidation::FormBuilder

Inherits:
ActionView::Helpers::FormBuilder
  • Object
show all
Extended by:
MapType
Includes:
Inputs
Defined in:
lib/simple_form_with_client_validation/form_builder.rb

Constant Summary collapse

ACTIONS =

When action is create or update, we still should use new and edit

{
  :create => :new,
  :update => :edit
}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from MapType

extended, map_type

Constructor Details

#initializeFormBuilder

:nodoc:



34
35
36
37
38
# File 'lib/simple_form_with_client_validation/form_builder.rb', line 34

def initialize(*) #:nodoc:
  super
  @defaults = options[:defaults]
  @wrapper  = SimpleFormWithClientValidation.wrapper(options[:wrapper] || SimpleFormWithClientValidation.default_wrapper)
end

Instance Attribute Details

#objectObject (readonly)

Returns the value of attribute object.



5
6
7
# File 'lib/simple_form_with_client_validation/form_builder.rb', line 5

def object
  @object
end

#object_nameObject (readonly)

Returns the value of attribute object_name.



5
6
7
# File 'lib/simple_form_with_client_validation/form_builder.rb', line 5

def object_name
  @object_name
end

#templateObject (readonly)

Returns the value of attribute template.



5
6
7
# File 'lib/simple_form_with_client_validation/form_builder.rb', line 5

def template
  @template
end

#wrapperObject (readonly)

Returns the value of attribute wrapper.



5
6
7
# File 'lib/simple_form_with_client_validation/form_builder.rb', line 5

def wrapper
  @wrapper
end

Class Method Details

.discovery_cacheObject



30
31
32
# File 'lib/simple_form_with_client_validation/form_builder.rb', line 30

def self.discovery_cache
  @discovery_cache ||= {}
end

Instance Method Details

#association(association, options = {}, &block) ⇒ Object

Helper for dealing with association selects/radios, generating the collection automatically. It’s just a wrapper to input, so all options supported in input are also supported by association. Some extra options can also be given:

Examples

simple_form_for @user do |f|
  f.association :company          # Company.all
end

f.association :company, :collection => Company.all(:order => 'name')
# Same as using :order option, but overriding collection

Block

When a block is given, association simple behaves as a proxy to simple_fields_for:

f.association :company do |c|
  c.input :name
  c.input :type
end

From the options above, only :collection can also be supplied.

Raises:

  • (ArgumentError)


168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/simple_form_with_client_validation/form_builder.rb', line 168

def association(association, options={}, &block)
  options = options.dup

  return simple_fields_for(*[association,
    options.delete(:collection), options].compact, &block) if block_given?

  raise ArgumentError, "Association cannot be used in forms not associated with an object" unless @object

  reflection = find_association_reflection(association)
  raise "Association #{association.inspect} not found" unless reflection

  options[:as] ||= :select
  options[:collection] ||= reflection.klass.all(reflection.options.slice(:conditions, :order))

  attribute = case reflection.macro
    when :belongs_to
      (reflection.respond_to?(:options) && reflection.options[:foreign_key]) || :"#{reflection.name}_id"
    when :has_one
      raise ":has_one associations are not supported by f.association"
    else
      if options[:as] == :select
        html_options = options[:input_html] ||= {}
        html_options[:size]   ||= 5
        html_options[:multiple] = true unless html_options.key?(:multiple)
      end

      # Force the association to be preloaded for performance.
      if options[:preload] != false && object.respond_to?(association)
        target = object.send(association)
        target.to_a if target.respond_to?(:to_a)
      end

      :"#{reflection.name.to_s.singularize}_ids"
  end

  input(attribute, options.merge(:reflection => reflection))
end

#button(type, *args, &block) ⇒ Object



218
219
220
221
222
223
224
225
226
227
# File 'lib/simple_form_with_client_validation/form_builder.rb', line 218

def button(type, *args, &block)
  options = args.extract_options!.dup
  options[:class] = [SimpleFormWithClientValidation.button_class, options[:class]].compact
  args << options
  if respond_to?("#{type}_button")
    send("#{type}_button", *args, &block)
  else
    send(type, *args, &block)
  end
end

#button_buttonObject

Creates a button:

form_for @user do |f|
  f.button :submit
end

It just acts as a proxy to method name given. We also alias original Rails button implementation (3.2 forward (to delegate to the original when calling ‘f.button :button`.

TODO: remove if condition when supporting only Rails 3.2 forward.



217
# File 'lib/simple_form_with_client_validation/form_builder.rb', line 217

alias_method :button_button, :button

#error(attribute_name, options = {}) ⇒ Object

Creates an error tag based on the given attribute, only when the attribute contains errors. All the given options are sent as :error_html.

Examples

f.error :name
f.error :name, :id => "cool_error"


237
238
239
240
241
242
243
244
245
# File 'lib/simple_form_with_client_validation/form_builder.rb', line 237

def error(attribute_name, options={})
  options = options.dup

  options[:error_html] = options.except(:error_tag, :error_prefix, :error_method)
  column      = find_attribute_column(attribute_name)
  input_type  = default_input_type(attribute_name, column, options)
  wrapper.find(:error).
    render(SimpleFormWithClientValidation::Inputs::Base.new(self, attribute_name, column, input_type, options))
end

#error_notification(options = {}) ⇒ Object

Creates an error notification message that only appears when the form object has some error. You can give a specific message with the :message option, otherwise it will look for a message using I18n. All other options given are passed straight as html options to the html tag.

Examples

f.error_notification
f.error_notification :message => 'Something went wrong'
f.error_notification :id => 'user_error_message', :class => 'form_error'


327
328
329
# File 'lib/simple_form_with_client_validation/form_builder.rb', line 327

def error_notification(options={})
  SimpleFormWithClientValidation::ErrorNotification.new(self, options).render
end

#full_error(attribute_name, options = {}) ⇒ Object

Return the error but also considering its name. This is used when errors for a hidden field need to be shown.

Examples

f.full_error :token #=> <span class="error">Token is invalid</span>


254
255
256
257
258
259
260
261
262
263
264
# File 'lib/simple_form_with_client_validation/form_builder.rb', line 254

def full_error(attribute_name, options={})
  options = options.dup

  options[:error_prefix] ||= if object.class.respond_to?(:human_attribute_name)
    object.class.human_attribute_name(attribute_name.to_s)
  else
    attribute_name.to_s.humanize
  end

  error(attribute_name, options)
end

#hint(attribute_name, options = {}) ⇒ Object

Creates a hint tag for the given attribute. Accepts a symbol indicating an attribute for I18n lookup or a string. All the given options are sent as :hint_html.

Examples

f.hint :name # Do I18n lookup
f.hint :name, :id => "cool_hint"
f.hint "Don't forget to accept this"


276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
# File 'lib/simple_form_with_client_validation/form_builder.rb', line 276

def hint(attribute_name, options={})
  options = options.dup

  options[:hint_html] = options.except(:hint_tag, :hint)
  if attribute_name.is_a?(String)
    options[:hint] = attribute_name
    attribute_name, column, input_type = nil, nil, nil
  else
    column      = find_attribute_column(attribute_name)
    input_type  = default_input_type(attribute_name, column, options)
  end

  wrapper.find(:hint).
    render(SimpleFormWithClientValidation::Inputs::Base.new(self, attribute_name, column, input_type, options))
end

#input(attribute_name, options = {}, &block) ⇒ Object Also known as: attribute

Basic input helper, combines all components in the stack to generate input html based on options the user define and some guesses through database column information. By default a call to input will generate label + input + hint (when defined) + errors (when exists), and all can be configured inside a wrapper html.

Examples

# Imagine @user has error "can't be blank" on name
simple_form_for @user do |f|
  f.input :name, :hint => 'My hint'
end

This is the output html (only the input portion, not the form):



My hint
can't be blank

Each database type will render a default input, based on some mappings and heuristic to determine which is the best option.

You have some options for the input to enable/disable some functions:

:as => allows you to define the input type you want, for instance you
       can use it to generate a text field for a date column.

:required => defines whether this attribute is required or not. True
            by default.

The fact SimpleFormWithClientValidation is built in components allow the interface to be unified. So, for instance, if you need to disable :hint for a given input, you can pass :hint => false. The same works for :error, :label and :wrapper.

Besides the html for any component can be changed. So, if you want to change the label html you just need to give a hash to :label_html. To configure the input html, supply :input_html instead and so on.

Options

Some inputs, as datetime, time and select allow you to give extra options, like prompt and/or include blank. Such options are given in plainly:

f.input :created_at, :include_blank => true

Collection

When playing with collections (:radio_buttons, :check_boxes and :select inputs), you have three extra options:

:collection => use to determine the collection to generate the radio or select

:label_method => the method to apply on the array collection to get the label

:value_method => the method to apply on the array collection to get the value

Priority

Some inputs, as :time_zone and :country accepts a :priority option. If none is given SimpleFormWithClientValidation.time_zone_priority and

SimpleFormWithClientValidation.country_priority are used respectivelly.


106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/simple_form_with_client_validation/form_builder.rb', line 106

def input(attribute_name, options={}, &block)
  options = @defaults.deep_dup.deep_merge(options) if @defaults
  
  #SimpleFormWithClientValidation.wrapper(name) is a module method that 
  # Retrieves a given wrapper
  chosen =
    if name = options[:wrapper]
      name.respond_to?(:render) ? name : SimpleFormWithClientValidation.wrapper(name)
    else
      wrapper
    end

  chosen.render find_input(attribute_name, options, &block)
end

#input_field(attribute_name, options = {}) ⇒ Object

Creates a input tag for the given attribute. All the given options are sent as :input_html.

Examples

simple_form_for @user do |f|
  f.input_field :name
end

This is the output html (only the input portion, not the form):

<input class="string required" id="user_name" maxlength="100"
   name="user[name]" size="100" type="text" value="Carlos" />


136
137
138
139
140
# File 'lib/simple_form_with_client_validation/form_builder.rb', line 136

def input_field(attribute_name, options={})
  options = options.dup
  options[:input_html] = options.except(:as, :collection, :label_method, :value_method)
  SimpleFormWithClientValidation::Wrappers::Root.new([:input], :wrapper => false).render find_input(attribute_name, options)
end

#label(attribute_name, *args) ⇒ Object

Creates a default label tag for the given attribute. You can give a label through the :label option or using i18n. All the given options are sent as :label_html.

Examples

f.label :name                     # Do I18n lookup
f.label :name, "Name"             # Same behavior as Rails, do not add required tag
f.label :name, :label => "Name"   # Same as above, but adds required tag

f.label :name, :required => false
f.label :name, :id => "cool_label"


305
306
307
308
309
310
311
312
313
314
# File 'lib/simple_form_with_client_validation/form_builder.rb', line 305

def label(attribute_name, *args)
  return super if args.first.is_a?(String) || block_given?

  options = args.extract_options!.dup
  options[:label_html] = options.except(:label, :required, :as)

  column      = find_attribute_column(attribute_name)
  input_type  = default_input_type(attribute_name, column, options)
  SimpleFormWithClientValidation::Inputs::Base.new(self, attribute_name, column, input_type, options).label
end

#lookup_actionObject

The action to be used in lookup.



350
351
352
353
354
355
356
357
# File 'lib/simple_form_with_client_validation/form_builder.rb', line 350

def lookup_action
  @lookup_action ||= begin
    action = template.controller.action_name
    return unless action
    action = action.to_sym
    ACTIONS[action] || action
  end
end

#lookup_model_namesObject

Extract the model names from the object_name mess, ignoring numeric and explicit child indexes.

Example:

route[0][1]

“route”, “blocks”, “blocks_learning_object”, “foo”


339
340
341
342
343
344
345
346
347
# File 'lib/simple_form_with_client_validation/form_builder.rb', line 339

def lookup_model_names
  @lookup_model_names ||= begin
    child_index = options[:child_index]
    names = object_name.to_s.scan(/([a-zA-Z_]+)/).flatten
    names.delete(child_index) if child_index
    names.each { |name| name.gsub!('_attributes', '') }
    names.freeze
  end
end