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 CRM
.api(model
.crmEntityName
, 'create', model
.toJSON(), apiOptions
);
77 var apiAction
= (method
== 'delete') ? 'delete' : 'get';
78 var params
= model
.toCrmCriteria();
80 apiOptions
.error({is_error
: 1, error_message
: 'Missing ID for ' + model
.crmEntityName
});
83 CRM
.api(model
.crmEntityName
, apiAction
, params
, apiOptions
);
86 apiOptions
.error({is_error
: 1, error_message
: "CRM.Backbone.sync(" + method
+ ") not implemented for models"});
92 * Connect a "model" class to CiviCRM's APIv3
96 * var ContactModel = Backbone.Model.extend({});
97 * CRM.Backbone.extendModel(ContactModel, "Contact");
100 * c = new ContactModel({id: 3});
104 * @param Class ModelClass
105 * @param string crmEntityName APIv3 entity name, such as "Contact" or "CustomField"
106 * @see tests/qunit/crm-backbone
108 CRM
.Backbone
.extendModel = function(ModelClass
, crmEntityName
) {
109 // Defaults - if specified in ModelClass, preserve
110 _
.defaults(ModelClass
.prototype, {
111 crmEntityName
: crmEntityName
,
112 toCrmCriteria: function() {
113 return (this.get('id')) ? {id
: this.get('id')} : {};
116 // Overrides - if specified in ModelClass, replace
117 _
.extend(ModelClass
.prototype, {
118 sync
: CRM
.Backbone
.sync
123 * Configure a model class to track whether a model has unsaved changes.
126 * - setModified() - flag the model as modified/dirty
127 * - isSaved() - return true if there have been no changes to the data since the last fetch or save
129 * - saved(object model, bool is_saved) - triggered whenever isSaved() value would change
131 * Note: You should not directly call isSaved() within the context of the success/error/sync callback;
132 * I haven't found a way to make isSaved() behave correctly within these callbacks without patching
133 * Backbone. Instead, attach an event listener to the 'saved' event.
137 CRM
.Backbone
.trackSaved = function(ModelClass
) {
138 // Retain references to some of the original class's functions
139 var Parent
= _
.pick(ModelClass
.prototype, 'initialize', 'save', 'fetch');
142 var onSyncSuccess = function() {
143 this._modified
= false;
144 if (this._oldModified
.length
> 0) {
145 this._oldModified
.pop();
147 this.trigger('saved', this, this.isSaved());
149 var onSaveError = function() {
150 if (this._oldModified
.length
> 0) {
151 this._modified
= this._oldModified
.pop();
152 this.trigger('saved', this, this.isSaved());
156 // Defaults - if specified in ModelClass, preserve
157 _
.defaults(ModelClass
.prototype, {
158 isSaved: function() {
159 var result
= !this.isNew() && !this.isModified();
162 isModified: function() {
163 return this._modified
;
165 _saved_onchange: function(model
, options
) {
166 if (options
.parse
) return;
167 // console.log('change', model.changedAttributes(), model.previousAttributes());
170 setModified: function() {
171 var oldModified
= this._modified
;
172 this._modified
= true;
174 this.trigger('saved', this, this.isSaved());
179 // Overrides - if specified in ModelClass, replace
180 _
.extend(ModelClass
.prototype, {
181 initialize: function(options
) {
182 this._modified
= false;
183 this._oldModified
= [];
184 this.listenTo(this, 'change', this._saved_onchange
);
185 this.listenTo(this, 'error', onSaveError
);
186 this.listenTo(this, 'sync', onSyncSuccess
);
187 if (Parent
.initialize
) {
188 return Parent
.initialize
.apply(this, arguments
);
192 // we'll assume success
193 this._oldModified
.push(this._modified
);
194 return Parent
.save
.apply(this, arguments
);
197 this._oldModified
.push(this._modified
);
198 return Parent
.fetch
.apply(this, arguments
);
204 * Configure a model class to support client-side soft deletion.
205 * One can call "model.setDeleted(BOOLEAN)" to flag an entity for
206 * deletion (or not) -- however, deletion will be deferred until save()
210 * setSoftDeleted(boolean) - flag the model as deleted (or not-deleted)
211 * isSoftDeleted() - determine whether model has been soft-deleted
213 * softDelete(model, is_deleted) -- change value of is_deleted
217 CRM
.Backbone
.trackSoftDelete = function(ModelClass
) {
218 // Retain references to some of the original class's functions
219 var Parent
= _
.pick(ModelClass
.prototype, 'save');
221 // Defaults - if specified in ModelClass, preserve
222 _
.defaults(ModelClass
.prototype, {
223 is_soft_deleted
: false,
224 setSoftDeleted: function(is_deleted
) {
225 if (this.is_soft_deleted
!= is_deleted
) {
226 this.is_soft_deleted
= is_deleted
;
227 this.trigger('softDelete', this, is_deleted
);
228 if (this.setModified
) this.setModified(); // FIXME: ugly interaction, trackSoftDelete-trackSaved
231 isSoftDeleted: function() {
232 return this.is_soft_deleted
;
236 // Overrides - if specified in ModelClass, replace
237 _
.extend(ModelClass
.prototype, {
238 save: function(attributes
, options
) {
239 if (this.isSoftDeleted()) {
240 return this.destroy(options
);
242 return Parent
.save
.apply(this, arguments
);
249 * Connect a "collection" class to CiviCRM's APIv3
251 * Note: the collection supports a special property, crmCriteria, which is an array of
252 * query options to send to the API.
256 * var ContactModel = Backbone.Model.extend({});
257 * CRM.Backbone.extendModel(ContactModel, "Contact");
258 * var ContactCollection = Backbone.Collection.extend({
259 * model: ContactModel
261 * CRM.Backbone.extendCollection(ContactCollection);
264 * var c = new ContactCollection([], {
265 * crmCriteria: {contact_type: 'Organization'}
268 * c.get(123).set('property', 'value');
269 * c.get(456).setDeleted(true);
273 * @param Class CollectionClass
274 * @see tests/qunit/crm-backbone
276 CRM
.Backbone
.extendCollection = function(CollectionClass
) {
277 var origInit
= CollectionClass
.prototype.initialize
;
278 // Defaults - if specified in CollectionClass, preserve
279 _
.defaults(CollectionClass
.prototype, {
280 crmEntityName
: CollectionClass
.prototype.model
.prototype.crmEntityName
,
281 toCrmCriteria: function() {
282 return (this.crmCriteria
) ? _
.extend({}, this.crmCriteria
) : {};
286 * Reconcile the server's collection with the client's collection.
287 * New/modified items from the client will be saved/updated on the
288 * server. Deleted items from the client will be deleted on the
291 * @param Object options - accepts "success" and "error" callbacks
293 save: function(options
) {
294 options
|| (options
= {});
295 var collection
= this;
296 var success
= options
.success
;
297 options
.success = function(resp
) {
298 // Ensure attributes are restored during synchronous saves.
299 collection
.reset(resp
, options
);
300 if (success
) success(collection
, resp
, options
);
301 // collection.trigger('sync', collection, resp, options);
303 wrapError(collection
, options
);
305 return this.sync('crm-replace', this, options
)
308 // Overrides - if specified in CollectionClass, replace
309 _
.extend(CollectionClass
.prototype, {
310 sync
: CRM
.Backbone
.sync
,
311 initialize: function(models
, options
) {
312 options
|| (options
= {});
313 if (options
.crmCriteria
) {
314 this.crmCriteria
= options
.crmCriteria
;
317 return origInit
.apply(this, arguments
);
322 // filter models list, excluding any soft-deleted items
323 this.each(function(model
) {
324 // if model doesn't track soft-deletes
325 // or if model tracks soft-deletes and wasn't soft-deleted
326 if (!model
.isSoftDeleted
|| !model
.isSoftDeleted()) {
327 result
.push(model
.toJSON());
336 * Find a single record, or create a new record.
338 * @param Object options:
339 * - CollectionClass: class
340 * - crmCriteria: Object values to search/default on
341 * - defaults: Object values to put on newly created model (if needed)
342 * - success: function(model)
343 * - error: function(collection, error)
345 CRM
.Backbone
.findCreate = function(options
) {
346 options
|| (options
= {});
347 var collection
= new options
.CollectionClass([], {
348 crmCriteria
: options
.crmCriteria
351 success: function(collection
) {
352 if (collection
.length
== 0) {
353 var attrs
= _
.extend({}, collection
.crmCriteria
, options
.defaults
|| {});
354 var model
= collection
._prepareModel(attrs
, options
);
355 options
.success(model
);
356 } else if (collection
.length
== 1) {
357 options
.success(collection
.first());
359 options
.error(collection
, {
361 error_message
: 'Too many matches'
365 error: function(collection
, errorData
) {
367 options
.error(collection
, errorData
);
374 CRM
.Backbone
.Model
= Backbone
.Model
.extend({
376 * Return JSON version of model -- but only include fields that are
377 * listed in the 'schema'.
381 toStrictJSON: function() {
382 var schema
= this.schema
;
383 var result
= this.toJSON();
384 _
.each(result
, function(value
, key
) {
391 setRel: function(key
, value
, options
) {
392 this.rels
= this.rels
|| {};
393 if (this.rels
[key
] != value
) {
394 this.rels
[key
] = value
;
395 this.trigger("rel:" + key
, value
);
398 getRel: function(key
) {
399 return this.rels
? this.rels
[key
] : null;
403 CRM
.Backbone
.Collection
= Backbone
.Collection
.extend({
405 * Store 'key' on this.rel and automatically copy it to
410 * @param initialModels
412 initializeCopyToChildrenRelation: function(key
, value
, initialModels
) {
413 this.setRel(key
, value
, {silent
: true});
414 this.on('reset', this._copyToChildren
, this);
415 this.on('add', this._copyToChild
, this);
417 _copyToChildren: function() {
418 var collection
= this;
419 collection
.each(function(model
) {
420 collection
._copyToChild(model
);
423 _copyToChild: function(model
) {
424 _
.each(this.rels
, function(relValue
, relKey
) {
425 model
.setRel(relKey
, relValue
, {silent
: true});
428 setRel: function(key
, value
, options
) {
429 this.rels
= this.rels
|| {};
430 if (this.rels
[key
] != value
) {
431 this.rels
[key
] = value
;
432 this.trigger("rel:" + key
, value
);
435 getRel: function(key
) {
436 return this.rels
? this.rels
[key
] : null;
441 CRM.Backbone.Form = Backbone.Form.extend({
442 validate: function() {
443 // Add support for form-level validators
444 var errors = Backbone.Form.prototype.validate.apply(this, []) || {};
446 if (this.validators) {
447 _.each(this.validators, function(validator) {
448 var modelErrors = validator(this.getValue());
450 // The following if() has been copied-pasted from the parent's
451 // handling of model-validators. They are similar in that the errors are
452 // probably keyed by field names... but not necessarily, so we use _others
455 var isDictionary = _.isObject(modelErrors) && !_.isArray(modelErrors);
457 //If errors are not in object form then just store on the error object
459 errors._others = errors._others || [];
460 errors._others.push(modelErrors);
463 //Merge programmatic errors (requires model.validate() to return an object e.g. { fieldKey: 'error' })
465 _.each(modelErrors, function(val, key) {
466 //Set error on field if there isn't one already
467 if (self.fields[key] && !errors[key]) {
468 self.fields[key].setError(val);
473 //Otherwise add to '_others' key
474 errors._others = errors._others || [];
477 errors._others.push(tmpErr);
485 return _.isEmpty(errors) ? null : errors;
490 // Wrap an optional error callback with a fallback error event.
491 var wrapError = function (model
, options
) {
492 var error
= options
.error
;
493 options
.error = function(resp
) {
494 if (error
) error(model
, resp
, options
);
495 model
.trigger('error', model
, resp
, options
);