-
Notifications
You must be signed in to change notification settings - Fork 6
/
form_builder.rb
65 lines (54 loc) · 2.34 KB
/
form_builder.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
module Lev
class FormBuilder < ActionView::Helpers::FormBuilder
(
field_helpers.map(&:to_s) - %w(label check_box radio_button fields_for file_field)
).each do |selector|
class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
def #{selector}(method, options = {}) # def text_field(method, options = {})
set_value_if_available(method, options) # ... verbatim ...
mark_error_if_present(method, options) # ... verbatim ...
super(method, options) # ... verbatim ...
end # end
RUBY_EVAL
end
def check_box(method, options = {}, checked_value = "1", unchecked_value = "0")
options[:checked] = true if get_form_params_entry(method).to_i > 0
mark_error_if_present(method, options)
super(method, options, checked_value, unchecked_value)
end
def radio_button(method, tag_value, options = {})
options[:checked] = true if get_form_params_entry(method) == tag_value
mark_error_if_present(method, options)
super(method, tag_value, options)
end
def fields_for(record_name, record_object = nil, fields_options = {}, &block)
raise "Didn't put fields_for into LevitateFormBuilder yet"
end
protected
def get_form_params_entry(name)
@options[:params].present? ?
(@options[:params][@object_name].present? ?
@options[:params][@object_name][name] :
nil) :
nil
end
def has_error?(name)
@options[:errors].present? ? @options[:errors].has_offending_input?([@object_name, name]) : false
end
def set_value_if_available(method, options)
value = get_form_params_entry(method)
options[:value] ||= value if !value.nil?
end
def mark_error_if_present(method, options)
if has_error?(method)
options[:class] = [options[:class], Lev.configuration.form_error_class].compact.join(' ')
end
end
end
end
def lev_form_for(record_or_name_or_array, *args, &proc)
options = args.extract_options!
options[:params] = params
options[:errors] = handler_errors # @errors || (@handler_outcome ? @handler_outcome.errors : [])
form_for(record_or_name_or_array, *(args << options.merge(:builder => Lev::FormBuilder)), &proc)
end