powmedia/backbone-forms — pull request #175 by surfbuds (2013-01-22 15:47:15+00:00)
Title: Support for subSchema fields value setting via setValue()

Modified setValue function to enable setting subSchema field value and not just top level schema field.

Dot notation (e.g: user.identity.name.first) for the field key will be recognized and checked against the schema by checking the existence of each key down the path of the subSchema.

e.g:
```
// Set field value with key (dot notation),value pair
MyForm.setValue("geoloc.Lat", marker.position.lat() );
// Set field value with Object notation
MyForm.setValue({"geoloc.Lng": marker.position.lng()} );
```
What's been changed and added?
1 function modification (setValue) and 1 helper function added (verifyKey), see below:

```
setValue: function(prop, val) {
var verifyKey=Form.helpers.verifyKey;
if (typeof prop === 'string') {
if (verifyKey(this.schema,prop)) {
this.fields[prop].setValue(val);
}
} else if (_.isObject(prop)) {
var key;
for (key in prop) {
if (verifyKey(this.schema,key)) {
this.fields[key].setValue(prop[key]);
}
}
}
},
```

```
/**
* Used by setValue to enable setting field value for nested schema
* Verify validity of dot-notation key for nested models e.g. 'user.name.first'
*
* @param {Object} obj Schema
* @param {String} key Field key e.g. 'user.name.first'
* @return {Boolean}
* @api private
*/
helpers.verifyKey = function(obj, key) {
var r=/\./, fields, path;
if (r.test(key)) {
path = key.replace(/\./g, '.subSchema.');
fields = path.split(".");
}
else{
fields = [key];
}
var result = obj;
for (var i = 0, n = fields.length; i < n; i++) {
if (_.has(result, fields[i])) {
result = result[fields[i]];
}
else {
return false;
}
}
return true;
};

```