Skip to content

Commit

Permalink
Merge branch 'kobsy-new-serialize-form'
Browse files Browse the repository at this point in the history
  • Loading branch information
boblail committed Mar 9, 2016
2 parents c992b36 + 7d46575 commit 34bc3e4
Showing 1 changed file with 33 additions and 17 deletions.
50 changes: 33 additions & 17 deletions vendor/assets/javascripts/neat/model_editor.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -94,26 +94,42 @@ class window.Neat.ModelEditor extends Backbone.View
okToSave: (attributes)->
true

attributesFromForm: ($el)->
attributesFromForm: ($el) ->
attrs = {}
$el.find('input, select, textarea').each ->
elem = $(this)
elem = $(@)
name = elem.attr('name')
if name
elemType = elem.attr('type')
value = elem.val()

if name.substr(-2) == '[]'
name = name.substring(0, name.length - 2)
attrs[name] = attrs[name] || []
attrs[name].push elem.val()

else if elemType == 'checkbox' || elemType == 'radio'
attrs[name] = '' if typeof(attrs[name]) == 'undefined'
attrs[name] = value if elem.prop('checked')

else
attrs[name] = value
elemType = elem.attr('type')
value = elem.val()
return true unless name

# Parse out nested objects as represented in names
# person[address][zip]=63303 should be serialized to:
# person:
# address:
# zip: 63303
parts = _.without(name.split(/\[([^\]]+)\]/), '')
name = parts.pop()
isArray = false
while name is '[]'
isArray = true
name = parts.pop()
context = attrs
for part in parts
context = context[part] or (context[part] = {})

if (elemType == 'checkbox' || elemType == 'radio') && !elem.prop('checked')
return true

if isArray
# select with multiple=true will return
# an array of selected values, so we don't
# need to nest that array in another array
value = [value] unless _.isArray(value)
value = (context[name] || []).concat(value)

context[name] = value
true # Don't break out of the loop
attrs

destroy: (e)->
Expand Down

0 comments on commit 34bc3e4

Please sign in to comment.