2 var CRM
= (window
.CRM
) ? (window
.CRM
) : (window
.CRM
= {});
3 if (!CRM
.Backbone
) CRM
.Backbone
= {};
5 CRM
.Backbone
.Model
= Backbone
.Model
.extend({
7 * Return JSON version of model -- but only include fields that are
8 * listed in the 'schema'.
12 toStrictJSON: function() {
13 var schema
= this.schema
;
14 var result
= this.toJSON();
15 _
.each(result
, function(value
, key
){
22 setRel: function(key
, value
, options
) {
23 this.rels
= this.rels
|| {};
24 if (this.rels
[key
] != value
) {
25 this.rels
[key
] = value
;
26 this.trigger("rel:"+key
, value
);
29 getRel: function(key
) {
30 return this.rels
? this.rels
[key
] : null;
34 CRM
.Backbone
.Collection
= Backbone
.Collection
.extend({
36 * Store 'key' on this.rel and automatically copy it to
41 * @param initialModels
43 initializeCopyToChildrenRelation: function(key
, value
, initialModels
) {
44 this.setRel(key
, value
, {silent
: true});
45 this.on('reset', this._copyToChildren
, this);
46 this.on('add', this._copyToChild
, this);
48 _copyToChildren: function() {
49 var collection
= this;
50 collection
.each(function(model
){
51 collection
._copyToChild(model
);
54 _copyToChild: function(model
) {
55 _
.each(this.rels
, function(relValue
, relKey
){
56 model
.setRel(relKey
, relValue
, {silent
: true});
59 setRel: function(key
, value
, options
) {
60 this.rels
= this.rels
|| {};
61 if (this.rels
[key
] != value
) {
62 this.rels
[key
] = value
;
63 this.trigger("rel:"+key
, value
);
66 getRel: function(key
) {
67 return this.rels
? this.rels
[key
] : null;
72 CRM.Backbone.Form = Backbone.Form.extend({
73 validate: function() {
74 // Add support for form-level validators
75 var errors = Backbone.Form.prototype.validate.apply(this, []) || {};
77 if (this.validators) {
78 _.each(this.validators, function(validator) {
79 var modelErrors = validator(this.getValue());
81 // The following if() has been copied-pasted from the parent's
82 // handling of model-validators. They are similar in that the errors are
83 // probably keyed by field names... but not necessarily, so we use _others
86 var isDictionary = _.isObject(modelErrors) && !_.isArray(modelErrors);
88 //If errors are not in object form then just store on the error object
90 errors._others = errors._others || [];
91 errors._others.push(modelErrors);
94 //Merge programmatic errors (requires model.validate() to return an object e.g. { fieldKey: 'error' })
96 _.each(modelErrors, function(val, key) {
97 //Set error on field if there isn't one already
98 if (self.fields[key] && !errors[key]) {
99 self.fields[key].setError(val);
104 //Otherwise add to '_others' key
105 errors._others = errors._others || [];
108 errors._others.push(tmpErr);
116 return _.isEmpty(errors) ? null : errors;