lib/formotion/form/form.rb in formotion-0.5.1 vs lib/formotion/form/form.rb in formotion-1.0
- old
+ new
@@ -1,11 +1,11 @@
module Formotion
class Form < Formotion::Base
PROPERTIES = [
# By default, Formotion::Controller will set it's title to this
# (so navigation bars will reflect it).
- :title,
+ :title,
# If you want to have some internal id to track the form.
:id
]
PROPERTIES.each {|prop|
attr_accessor prop
@@ -85,11 +85,11 @@
#########################
# callbacks
# Stores the callback block when you do #submit.
# EX
- # @form.on_submit do
+ # @form.on_submit do
# do_something(@form.render)
# end
#
# EX
# @form.on_submit do |form|
@@ -101,17 +101,22 @@
# Triggers the #on_submit block
# Handles either zero or one arguments,
# as shown above.
def submit
+ if @on_submit_callback.nil?
+ p "`Form#submit` invoked without a callback, doing nothing."
+ return
+ end
+
if @on_submit_callback.arity == 0
@on_submit_callback.call
elsif @on_submit_callback.arity == 1
@on_submit_callback.call(self)
end
end
-
+
#########################
# Retreiving data
# A complete hashification of the Form
# EX
@@ -121,23 +126,23 @@
# => {title: 'My Title', id: 'anything'}
def to_hash
# super handles all of the ::PROPERTIES
h = super
h[:sections] = self.sections.collect { |section|
- section.to_hash
+ section.to_hash
}
recursive_delete_nil(h)
h
end
# A hashification with the user's inputted values
# and row keys.
# EX
# @form = Formotion::Form.new(sections: [{
# rows: [{
- # key: 'Email',
- # editable: true,
+ # key: 'Email',
+ # editable: true,
# title: 'Email'
# }]}])
# ...user plays with the Form...
# @form.render
# => {email: 'something@email.com'}
@@ -150,15 +155,33 @@
kv[section.key] = row.key
end
}
else
section.rows.each {|row|
- next if row.submit_button?
- kv[row.key] = row.value
+ next if row.button?
+ if row.template_parent
+ # If this row is part of a template
+ # use the parent's key
+ kv[row.template_parent.key] ||= []
+ kv[row.template_parent.key] << row.value
+ else
+ kv[row.key] ||= row.value
+ end
}
end
}
+ kv.merge! sub_render
kv.delete_if {|k, v| k.nil? }
+ kv
+ end
+
+ def sub_render
+ kv = {}
+ rows = sections.map(&:rows).flatten
+ subform_rows = rows.select{ |row| row.subform != nil }
+ subform_rows.each do |subform_row|
+ kv[subform_row.key] = subform_row.subform.to_form.render
+ end
kv
end
private
def recursive_delete_nil(h)
\ No newline at end of file