Skip to content

Instantly share code, notes, and snippets.

@nathggns
Last active August 29, 2015 14:08
Show Gist options
  • Save nathggns/792421b5970f0e95ce50 to your computer and use it in GitHub Desktop.
Save nathggns/792421b5970f0e95ce50 to your computer and use it in GitHub Desktop.
Helper function for dealing with cakephp form fields. Requires Lodash and jQuery.

Example:

HTML:

<form id="myForm">
    <label for="PermissionsWrite">Write</label>
    <input id="PermissionsWrite" type="checkbox" name="data[Permissions][]" value="Write" checked />
    
    <label for="PermissionsRead">Read</label>
    <input id="PermissionsRead" type="checkbox" name="data[Permissions][]" value="Read" />
    
    <label for="PermissionsLevel">Level</label>
    <input type="text" name="data[Permissions][level]" id="PermissionsLevel" value="admin" />
</form>

Javascript

CakePHP.Form.toJSON(document.getElementById('myForm'))
// "{"data[Permissions]":["Write"],"data[Permissions][level]":"admin"}"
var CakePHP = {
Form : {
parseIntoTree : function(name, value) {
if (typeof name !== 'string') {
return {};
}
var nameParts = name.split('[]');
return (function buildTreePart(val, idx) {
var part = nameParts[idx];
if (part.length) {
part = [_.zipObject([part], [val])];
} else {
part = [val];
}
if (!idx) {
return part;
} else {
return buildTreePart(part, idx - 1);
}
})(value, nameParts.length - 1)[0];
},
mergeTree : function(treeOne, treeTwo) {
if (_.isArray(treeOne) && _.isArray(treeTwo)) {
return treeOne.concat(treeTwo);
}
if (!_.isObject(treeOne) || !_.isObject(treeTwo)) {
return treeTwo;
}
return _.reduce(treeTwo, function(object, value, key) {
if (typeof object[key] !== 'undefined') {
value = CakePHP.Form.mergeTree(object[key], treeTwo[key]);
}
object[key] = value;
return object;
}, treeOne);
},
toJSON : function(node) {
return JSON.stringify(CakePHP.Form.toData(node));
},
getInputNodes : function(node) {
return $('input, textarea', node);
},
toData : function(formNode) {
return _.reduce(this.getInputNodes(formNode), function(object, inputNode) {
var $inputNode = $(inputNode);
if ($inputNode.attr('type') === 'checkbox' && !$inputNode.is(':checked')) {
return object;
}
return CakePHP.Form.mergeTree(
object,
CakePHP.Form.parseIntoTree($inputNode.attr('name'), $inputNode.val())
);
}, {});
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment