2 var CRM
= (window
.CRM
) ? (window
.CRM
) : (window
.CRM
= {});
3 if (!CRM
.Backbone
) CRM
.Backbone
= {};
6 * Backbone.sync provider which uses CRM.api() for I/O.
7 * To support CRUD operations, model classes must be defined with a "crmEntityName" property.
8 * To load collections using API queries, set the "crmCriteria" property or override the
9 * method "toCrmCriteria".
11 * @param method Accepts normal Backbone.sync methods; also accepts "crm-replace"
14 * @see tests/qunit/crm-backbone
16 CRM
.Backbone
.sync = function(method
, model
, options
) {
17 var isCollection
= _
.isArray(model
.models
);
21 success: function(data
) {
23 options
.success(_
.toArray(data
.values
));
25 error: function(data
) {
26 // CRM.api displays errors by default, but Backbone.sync
27 // protocol requires us to override "error". This restores
28 // the default behavior.
29 $().crmError(data
.error_message
, ts('Error'));
35 CRM
.api(model
.crmEntityName
, 'get', model
.toCrmCriteria(), apiOptions
);
37 // replace all entities matching "x.crmCriteria" with new entities in "x.models"
39 var params
= this.toCrmCriteria();
41 params
.values
= this.toJSON();
42 CRM
.api(model
.crmEntityName
, 'replace', params
, apiOptions
);
45 apiOptions
.error({is_error
: 1, error_message
: "CRM.Backbone.sync(" + method
+ ") not implemented for collections"});
49 // callback options to pass to CRM.api
51 success: function(data
) {
53 var values
= _
.toArray(data
['values']);
54 if (data
.count
== 1) {
55 options
.success(values
[0]);
58 data
.error_message
= ts("Expected exactly one response");
59 apiOptions
.error(data
);
62 error: function(data
) {
63 // CRM.api displays errors by default, but Backbone.sync
64 // protocol requires us to override "error". This restores
65 // the default behavior.
66 $().crmError(data
.error_message
, ts('Error'));
71 case 'create': // pass-through
73 var params
= model
.toJSON();
74 params
.options
|| (params
.options
= {});
75 params
.options
.reload
= 1;
76 if (!model
._isDuplicate
) {
77 CRM
.api(model
.crmEntityName
, 'create', params
, apiOptions
);
79 CRM
.api(model
.crmEntityName
, 'duplicate', params
, apiOptions
);
84 var apiAction
= (method
== 'delete') ? 'delete' : 'get';
85 var params
= model
.toCrmCriteria();
87 apiOptions
.error({is_error
: 1, error_message
: 'Missing ID for ' + model
.crmEntityName
});
90 CRM
.api(model
.crmEntityName
, apiAction
, params
, apiOptions
);
93 apiOptions
.error({is_error
: 1, error_message
: "CRM.Backbone.sync(" + method
+ ") not implemented for models"});
99 * Connect a "model" class to CiviCRM's APIv3
103 * var ContactModel = Backbone.Model.extend({});
104 * CRM.Backbone.extendModel(ContactModel, "Contact");
107 * c = new ContactModel({id: 3});
111 * @param Class ModelClass
112 * @param string crmEntityName APIv3 entity name, such as "Contact" or "CustomField"
113 * @see tests/qunit/crm-backbone
115 CRM
.Backbone
.extendModel = function(ModelClass
, crmEntityName
) {
116 // Defaults - if specified in ModelClass, preserve
117 _
.defaults(ModelClass
.prototype, {
118 crmEntityName
: crmEntityName
,
119 toCrmCriteria: function() {
120 return (this.get('id')) ? {id
: this.get('id')} : {};
122 duplicate: function() {
123 var newModel
= new ModelClass(this.toJSON());
124 newModel
._isDuplicate
= true;
125 if (newModel
.setModified
) newModel
.setModified();
126 newModel
.listenTo(newModel
, 'sync', function(){
127 // may get called on subsequent resaves -- don't care!
128 delete newModel
._isDuplicate
;
133 // Overrides - if specified in ModelClass, replace
134 _
.extend(ModelClass
.prototype, {
135 sync
: CRM
.Backbone
.sync
140 * Configure a model class to track whether a model has unsaved changes.
143 * - setModified() - flag the model as modified/dirty
144 * - isSaved() - return true if there have been no changes to the data since the last fetch or save
146 * - saved(object model, bool is_saved) - triggered whenever isSaved() value would change
148 * Note: You should not directly call isSaved() within the context of the success/error/sync callback;
149 * I haven't found a way to make isSaved() behave correctly within these callbacks without patching
150 * Backbone. Instead, attach an event listener to the 'saved' event.
154 CRM
.Backbone
.trackSaved = function(ModelClass
) {
155 // Retain references to some of the original class's functions
156 var Parent
= _
.pick(ModelClass
.prototype, 'initialize', 'save', 'fetch');
159 var onSyncSuccess = function() {
160 this._modified
= false;
161 if (this._oldModified
.length
> 0) {
162 this._oldModified
.pop();
164 this.trigger('saved', this, this.isSaved());
166 var onSaveError = function() {
167 if (this._oldModified
.length
> 0) {
168 this._modified
= this._oldModified
.pop();
169 this.trigger('saved', this, this.isSaved());
173 // Defaults - if specified in ModelClass, preserve
174 _
.defaults(ModelClass
.prototype, {
175 isSaved: function() {
176 var result
= !this.isNew() && !this.isModified();
179 isModified: function() {
180 return this._modified
;
182 _saved_onchange: function(model
, options
) {
183 if (options
.parse
) return;
184 // console.log('change', model.changedAttributes(), model.previousAttributes());
187 setModified: function() {
188 var oldModified
= this._modified
;
189 this._modified
= true;
191 this.trigger('saved', this, this.isSaved());
196 // Overrides - if specified in ModelClass, replace
197 _
.extend(ModelClass
.prototype, {
198 initialize: function(options
) {
199 this._modified
= false;
200 this._oldModified
= [];
201 this.listenTo(this, 'change', this._saved_onchange
);
202 this.listenTo(this, 'error', onSaveError
);
203 this.listenTo(this, 'sync', onSyncSuccess
);
204 if (Parent
.initialize
) {
205 return Parent
.initialize
.apply(this, arguments
);
209 // we'll assume success
210 this._oldModified
.push(this._modified
);
211 return Parent
.save
.apply(this, arguments
);
214 this._oldModified
.push(this._modified
);
215 return Parent
.fetch
.apply(this, arguments
);
221 * Configure a model class to support client-side soft deletion.
222 * One can call "model.setDeleted(BOOLEAN)" to flag an entity for
223 * deletion (or not) -- however, deletion will be deferred until save()
227 * setSoftDeleted(boolean) - flag the model as deleted (or not-deleted)
228 * isSoftDeleted() - determine whether model has been soft-deleted
230 * softDelete(model, is_deleted) -- change value of is_deleted
234 CRM
.Backbone
.trackSoftDelete = function(ModelClass
) {
235 // Retain references to some of the original class's functions
236 var Parent
= _
.pick(ModelClass
.prototype, 'save');
238 // Defaults - if specified in ModelClass, preserve
239 _
.defaults(ModelClass
.prototype, {
240 is_soft_deleted
: false,
241 setSoftDeleted: function(is_deleted
) {
242 if (this.is_soft_deleted
!= is_deleted
) {
243 this.is_soft_deleted
= is_deleted
;
244 this.trigger('softDelete', this, is_deleted
);
245 if (this.setModified
) this.setModified(); // FIXME: ugly interaction, trackSoftDelete-trackSaved
248 isSoftDeleted: function() {
249 return this.is_soft_deleted
;
253 // Overrides - if specified in ModelClass, replace
254 _
.extend(ModelClass
.prototype, {
255 save: function(attributes
, options
) {
256 if (this.isSoftDeleted()) {
257 return this.destroy(options
);
259 return Parent
.save
.apply(this, arguments
);
266 * Connect a "collection" class to CiviCRM's APIv3
268 * Note: the collection supports a special property, crmCriteria, which is an array of
269 * query options to send to the API.
273 * var ContactModel = Backbone.Model.extend({});
274 * CRM.Backbone.extendModel(ContactModel, "Contact");
275 * var ContactCollection = Backbone.Collection.extend({
276 * model: ContactModel
278 * CRM.Backbone.extendCollection(ContactCollection);
281 * var c = new ContactCollection([], {
282 * crmCriteria: {contact_type: 'Organization'}
285 * c.get(123).set('property', 'value');
286 * c.get(456).setDeleted(true);
290 * @param Class CollectionClass
291 * @see tests/qunit/crm-backbone
293 CRM
.Backbone
.extendCollection = function(CollectionClass
) {
294 var origInit
= CollectionClass
.prototype.initialize
;
295 // Defaults - if specified in CollectionClass, preserve
296 _
.defaults(CollectionClass
.prototype, {
297 crmEntityName
: CollectionClass
.prototype.model
.prototype.crmEntityName
,
298 toCrmCriteria: function() {
299 return (this.crmCriteria
) ? _
.extend({}, this.crmCriteria
) : {};
303 * Reconcile the server's collection with the client's collection.
304 * New/modified items from the client will be saved/updated on the
305 * server. Deleted items from the client will be deleted on the
308 * @param Object options - accepts "success" and "error" callbacks
310 save: function(options
) {
311 options
|| (options
= {});
312 var collection
= this;
313 var success
= options
.success
;
314 options
.success = function(resp
) {
315 // Ensure attributes are restored during synchronous saves.
316 collection
.reset(resp
, options
);
317 if (success
) success(collection
, resp
, options
);
318 // collection.trigger('sync', collection, resp, options);
320 wrapError(collection
, options
);
322 return this.sync('crm-replace', this, options
)
325 // Overrides - if specified in CollectionClass, replace
326 _
.extend(CollectionClass
.prototype, {
327 sync
: CRM
.Backbone
.sync
,
328 initialize: function(models
, options
) {
329 options
|| (options
= {});
330 if (options
.crmCriteria
) {
331 this.crmCriteria
= options
.crmCriteria
;
334 return origInit
.apply(this, arguments
);
339 // filter models list, excluding any soft-deleted items
340 this.each(function(model
) {
341 // if model doesn't track soft-deletes
342 // or if model tracks soft-deletes and wasn't soft-deleted
343 if (!model
.isSoftDeleted
|| !model
.isSoftDeleted()) {
344 result
.push(model
.toJSON());
353 * Find a single record, or create a new record.
355 * @param Object options:
356 * - CollectionClass: class
357 * - crmCriteria: Object values to search/default on
358 * - defaults: Object values to put on newly created model (if needed)
359 * - success: function(model)
360 * - error: function(collection, error)
362 CRM
.Backbone
.findCreate = function(options
) {
363 options
|| (options
= {});
364 var collection
= new options
.CollectionClass([], {
365 crmCriteria
: options
.crmCriteria
368 success: function(collection
) {
369 if (collection
.length
== 0) {
370 var attrs
= _
.extend({}, collection
.crmCriteria
, options
.defaults
|| {});
371 var model
= collection
._prepareModel(attrs
, options
);
372 options
.success(model
);
373 } else if (collection
.length
== 1) {
374 options
.success(collection
.first());
376 options
.error(collection
, {
378 error_message
: 'Too many matches'
382 error: function(collection
, errorData
) {
384 options
.error(collection
, errorData
);
391 CRM
.Backbone
.Model
= Backbone
.Model
.extend({
393 * Return JSON version of model -- but only include fields that are
394 * listed in the 'schema'.
398 toStrictJSON: function() {
399 var schema
= this.schema
;
400 var result
= this.toJSON();
401 _
.each(result
, function(value
, key
) {
408 setRel: function(key
, value
, options
) {
409 this.rels
= this.rels
|| {};
410 if (this.rels
[key
] != value
) {
411 this.rels
[key
] = value
;
412 this.trigger("rel:" + key
, value
);
415 getRel: function(key
) {
416 return this.rels
? this.rels
[key
] : null;
420 CRM
.Backbone
.Collection
= Backbone
.Collection
.extend({
422 * Store 'key' on this.rel and automatically copy it to
427 * @param initialModels
429 initializeCopyToChildrenRelation: function(key
, value
, initialModels
) {
430 this.setRel(key
, value
, {silent
: true});
431 this.on('reset', this._copyToChildren
, this);
432 this.on('add', this._copyToChild
, this);
434 _copyToChildren: function() {
435 var collection
= this;
436 collection
.each(function(model
) {
437 collection
._copyToChild(model
);
440 _copyToChild: function(model
) {
441 _
.each(this.rels
, function(relValue
, relKey
) {
442 model
.setRel(relKey
, relValue
, {silent
: true});
445 setRel: function(key
, value
, options
) {
446 this.rels
= this.rels
|| {};
447 if (this.rels
[key
] != value
) {
448 this.rels
[key
] = value
;
449 this.trigger("rel:" + key
, value
);
452 getRel: function(key
) {
453 return this.rels
? this.rels
[key
] : null;
458 CRM.Backbone.Form = Backbone.Form.extend({
459 validate: function() {
460 // Add support for form-level validators
461 var errors = Backbone.Form.prototype.validate.apply(this, []) || {};
463 if (this.validators) {
464 _.each(this.validators, function(validator) {
465 var modelErrors = validator(this.getValue());
467 // The following if() has been copied-pasted from the parent's
468 // handling of model-validators. They are similar in that the errors are
469 // probably keyed by field names... but not necessarily, so we use _others
472 var isDictionary = _.isObject(modelErrors) && !_.isArray(modelErrors);
474 //If errors are not in object form then just store on the error object
476 errors._others = errors._others || [];
477 errors._others.push(modelErrors);
480 //Merge programmatic errors (requires model.validate() to return an object e.g. { fieldKey: 'error' })
482 _.each(modelErrors, function(val, key) {
483 //Set error on field if there isn't one already
484 if (self.fields[key] && !errors[key]) {
485 self.fields[key].setError(val);
490 //Otherwise add to '_others' key
491 errors._others = errors._others || [];
494 errors._others.push(tmpErr);
502 return _.isEmpty(errors) ? null : errors;
507 // Wrap an optional error callback with a fallback error event.
508 var wrapError = function (model
, options
) {
509 var error
= options
.error
;
510 options
.error = function(resp
) {
511 if (error
) error(model
, resp
, options
);
512 model
.trigger('error', model
, resp
, options
);