1 (function($, _
, Backbone
) {
2 if (!CRM
.Backbone
) CRM
.Backbone
= {};
5 * Backbone.sync provider which uses CRM.api() for I/O.
6 * To support CRUD operations, model classes must be defined with a "crmEntityName" property.
7 * To load collections using API queries, set the "crmCriteria" property or override the
8 * method "toCrmCriteria".
10 * @param method Accepts normal Backbone.sync methods; also accepts "crm-replace"
13 * @see tests/qunit/crm-backbone
15 CRM
.Backbone
.sync = function(method
, model
, options
) {
16 var isCollection
= _
.isArray(model
.models
);
18 var apiOptions
, params
;
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
, model
.toCrmAction('get'), model
.toCrmCriteria(), apiOptions
);
37 // replace all entities matching "x.crmCriteria" with new entities in "x.models"
39 params
= this.toCrmCriteria();
41 params
.values
= this.toJSON();
42 CRM
.api(model
.crmEntityName
, model
.toCrmAction('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 params
= model
.toJSON();
74 if (!params
.options
) params
.options
= {};
75 params
.options
.reload
= 1;
76 if (!model
._isDuplicate
) {
77 CRM
.api(model
.crmEntityName
, model
.toCrmAction('create'), params
, apiOptions
);
79 CRM
.api(model
.crmEntityName
, model
.toCrmAction('duplicate'), params
, apiOptions
);
84 var apiAction
= (method
== 'delete') ? 'delete' : 'get';
85 params
= model
.toCrmCriteria();
87 apiOptions
.error({is_error
: 1, error_message
: 'Missing ID for ' + model
.crmEntityName
});
90 CRM
.api(model
.crmEntityName
, model
.toCrmAction(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 crmActions
: {}, // map: string backboneActionName => string serverSideActionName
120 crmReturn
: null, // array: list of fields to return
121 toCrmAction: function(action
) {
122 return this.crmActions
[action
] ? this.crmActions
[action
] : action
;
124 toCrmCriteria: function() {
125 var result
= (this.get('id')) ? {id
: this.get('id')} : {};
126 if (!_
.isEmpty(this.crmReturn
)) {
127 result
.return = this.crmReturn
;
131 duplicate: function() {
132 var newModel
= new ModelClass(this.toJSON());
133 newModel
._isDuplicate
= true;
134 if (newModel
.setModified
) newModel
.setModified();
135 newModel
.listenTo(newModel
, 'sync', function(){
136 // may get called on subsequent resaves -- don't care!
137 delete newModel
._isDuplicate
;
142 // Overrides - if specified in ModelClass, replace
143 _
.extend(ModelClass
.prototype, {
144 sync
: CRM
.Backbone
.sync
149 * Configure a model class to track whether a model has unsaved changes.
152 * - setModified() - flag the model as modified/dirty
153 * - isSaved() - return true if there have been no changes to the data since the last fetch or save
155 * - saved(object model, bool is_saved) - triggered whenever isSaved() value would change
157 * Note: You should not directly call isSaved() within the context of the success/error/sync callback;
158 * I haven't found a way to make isSaved() behave correctly within these callbacks without patching
159 * Backbone. Instead, attach an event listener to the 'saved' event.
163 CRM
.Backbone
.trackSaved = function(ModelClass
) {
164 // Retain references to some of the original class's functions
165 var Parent
= _
.pick(ModelClass
.prototype, 'initialize', 'save', 'fetch');
168 var onSyncSuccess = function() {
169 this._modified
= false;
170 if (this._oldModified
.length
> 0) {
171 this._oldModified
.pop();
173 this.trigger('saved', this, this.isSaved());
175 var onSaveError = function() {
176 if (this._oldModified
.length
> 0) {
177 this._modified
= this._oldModified
.pop();
178 this.trigger('saved', this, this.isSaved());
182 // Defaults - if specified in ModelClass, preserve
183 _
.defaults(ModelClass
.prototype, {
184 isSaved: function() {
185 var result
= !this.isNew() && !this.isModified();
188 isModified: function() {
189 return this._modified
;
191 _saved_onchange: function(model
, options
) {
192 if (options
.parse
) return;
193 // console.log('change', model.changedAttributes(), model.previousAttributes());
196 setModified: function() {
197 var oldModified
= this._modified
;
198 this._modified
= true;
200 this.trigger('saved', this, this.isSaved());
205 // Overrides - if specified in ModelClass, replace
206 _
.extend(ModelClass
.prototype, {
207 initialize: function(options
) {
208 this._modified
= false;
209 this._oldModified
= [];
210 this.listenTo(this, 'change', this._saved_onchange
);
211 this.listenTo(this, 'error', onSaveError
);
212 this.listenTo(this, 'sync', onSyncSuccess
);
213 if (Parent
.initialize
) {
214 return Parent
.initialize
.apply(this, arguments
);
218 // we'll assume success
219 this._oldModified
.push(this._modified
);
220 return Parent
.save
.apply(this, arguments
);
223 this._oldModified
.push(this._modified
);
224 return Parent
.fetch
.apply(this, arguments
);
230 * Configure a model class to support client-side soft deletion.
231 * One can call "model.setDeleted(BOOLEAN)" to flag an entity for
232 * deletion (or not) -- however, deletion will be deferred until save()
236 * setSoftDeleted(boolean) - flag the model as deleted (or not-deleted)
237 * isSoftDeleted() - determine whether model has been soft-deleted
239 * softDelete(model, is_deleted) -- change value of is_deleted
243 CRM
.Backbone
.trackSoftDelete = function(ModelClass
) {
244 // Retain references to some of the original class's functions
245 var Parent
= _
.pick(ModelClass
.prototype, 'save');
247 // Defaults - if specified in ModelClass, preserve
248 _
.defaults(ModelClass
.prototype, {
249 is_soft_deleted
: false,
250 setSoftDeleted: function(is_deleted
) {
251 if (this.is_soft_deleted
!= is_deleted
) {
252 this.is_soft_deleted
= is_deleted
;
253 this.trigger('softDelete', this, is_deleted
);
254 if (this.setModified
) this.setModified(); // FIXME: ugly interaction, trackSoftDelete-trackSaved
257 isSoftDeleted: function() {
258 return this.is_soft_deleted
;
262 // Overrides - if specified in ModelClass, replace
263 _
.extend(ModelClass
.prototype, {
264 save: function(attributes
, options
) {
265 if (this.isSoftDeleted()) {
266 return this.destroy(options
);
268 return Parent
.save
.apply(this, arguments
);
275 * Connect a "collection" class to CiviCRM's APIv3
277 * Note: the collection supports a special property, crmCriteria, which is an array of
278 * query options to send to the API.
282 * var ContactModel = Backbone.Model.extend({});
283 * CRM.Backbone.extendModel(ContactModel, "Contact");
284 * var ContactCollection = Backbone.Collection.extend({
285 * model: ContactModel
287 * CRM.Backbone.extendCollection(ContactCollection);
289 * // Use class (with passive criteria)
290 * var c = new ContactCollection([], {
291 * crmCriteria: {contact_type: 'Organization'}
294 * c.get(123).set('property', 'value');
295 * c.get(456).setDeleted(true);
298 * // Use class (with active criteria)
299 * var criteriaModel = new SomeModel({
300 * contact_type: 'Organization'
302 * var c = new ContactCollection([], {
303 * crmCriteriaModel: criteriaModel
306 * c.get(123).set('property', 'value');
307 * c.get(456).setDeleted(true);
312 * @param Class CollectionClass
313 * @see tests/qunit/crm-backbone
315 CRM
.Backbone
.extendCollection = function(CollectionClass
) {
316 var origInit
= CollectionClass
.prototype.initialize
;
317 // Defaults - if specified in CollectionClass, preserve
318 _
.defaults(CollectionClass
.prototype, {
319 crmEntityName
: CollectionClass
.prototype.model
.prototype.crmEntityName
,
320 crmActions
: {}, // map: string backboneActionName => string serverSideActionName
321 toCrmAction: function(action
) {
322 return this.crmActions
[action
] ? this.crmActions
[action
] : action
;
324 toCrmCriteria: function() {
325 var result
= (this.crmCriteria
) ? _
.extend({}, this.crmCriteria
) : {};
326 if (!_
.isEmpty(this.crmReturn
)) {
327 result
.return = this.crmReturn
;
328 } else if (this.model
&& !_
.isEmpty(this.model
.prototype.crmReturn
)) {
329 result
.return = this.model
.prototype.crmReturn
;
335 * Get an object which represents this collection's criteria
336 * as a live model. Any changes to the model will be applied
337 * to the collection, and the collection will be refreshed.
339 * @param criteriaModelClass
341 setCriteriaModel: function(criteriaModel
) {
342 var collection
= this;
343 this.crmCriteria
= criteriaModel
.toJSON();
344 this.listenTo(criteriaModel
, 'change', function() {
345 collection
.crmCriteria
= criteriaModel
.toJSON();
346 collection
.debouncedFetch();
350 debouncedFetch
: _
.debounce(function() {
351 this.fetch({reset
: true});
355 * Reconcile the server's collection with the client's collection.
356 * New/modified items from the client will be saved/updated on the
357 * server. Deleted items from the client will be deleted on the
360 * @param Object options - accepts "success" and "error" callbacks
362 save: function(options
) {
363 if (!options
) options
= {};
364 var collection
= this;
365 var success
= options
.success
;
366 options
.success = function(resp
) {
367 // Ensure attributes are restored during synchronous saves.
368 collection
.reset(resp
, options
);
369 if (success
) success(collection
, resp
, options
);
370 // collection.trigger('sync', collection, resp, options);
372 wrapError(collection
, options
);
374 return this.sync('crm-replace', this, options
);
377 // Overrides - if specified in CollectionClass, replace
378 _
.extend(CollectionClass
.prototype, {
379 sync
: CRM
.Backbone
.sync
,
380 initialize: function(models
, options
) {
381 if (!options
) options
= {};
382 if (options
.crmCriteriaModel
) {
383 this.setCriteriaModel(options
.crmCriteriaModel
);
384 } else if (options
.crmCriteria
) {
385 this.crmCriteria
= options
.crmCriteria
;
387 if (options
.crmActions
) {
388 this.crmActions
= _
.extend(this.crmActions
, options
.crmActions
);
391 return origInit
.apply(this, arguments
);
396 // filter models list, excluding any soft-deleted items
397 this.each(function(model
) {
398 // if model doesn't track soft-deletes
399 // or if model tracks soft-deletes and wasn't soft-deleted
400 if (!model
.isSoftDeleted
|| !model
.isSoftDeleted()) {
401 result
.push(model
.toJSON());
410 * Find a single record, or create a new record.
412 * @param Object options:
413 * - CollectionClass: class
414 * - crmCriteria: Object values to search/default on
415 * - defaults: Object values to put on newly created model (if needed)
416 * - success: function(model)
417 * - error: function(collection, error)
419 CRM
.Backbone
.findCreate = function(options
) {
420 if (!options
) options
= {};
421 var collection
= new options
.CollectionClass([], {
422 crmCriteria
: options
.crmCriteria
425 success: function(collection
) {
426 if (collection
.length
=== 0) {
427 var attrs
= _
.extend({}, collection
.crmCriteria
, options
.defaults
|| {});
428 var model
= collection
._prepareModel(attrs
, options
);
429 options
.success(model
);
430 } else if (collection
.length
== 1) {
431 options
.success(collection
.first());
433 options
.error(collection
, {
435 error_message
: 'Too many matches'
439 error: function(collection
, errorData
) {
441 options
.error(collection
, errorData
);
448 CRM
.Backbone
.Model
= Backbone
.Model
.extend({
450 * Return JSON version of model -- but only include fields that are
451 * listed in the 'schema'.
455 toStrictJSON: function() {
456 var schema
= this.schema
;
457 var result
= this.toJSON();
458 _
.each(result
, function(value
, key
) {
465 setRel: function(key
, value
, options
) {
466 this.rels
= this.rels
|| {};
467 if (this.rels
[key
] != value
) {
468 this.rels
[key
] = value
;
469 this.trigger("rel:" + key
, value
);
472 getRel: function(key
) {
473 return this.rels
? this.rels
[key
] : null;
477 CRM
.Backbone
.Collection
= Backbone
.Collection
.extend({
479 * Store 'key' on this.rel and automatically copy it to
484 * @param initialModels
486 initializeCopyToChildrenRelation: function(key
, value
, initialModels
) {
487 this.setRel(key
, value
, {silent
: true});
488 this.on('reset', this._copyToChildren
, this);
489 this.on('add', this._copyToChild
, this);
491 _copyToChildren: function() {
492 var collection
= this;
493 collection
.each(function(model
) {
494 collection
._copyToChild(model
);
497 _copyToChild: function(model
) {
498 _
.each(this.rels
, function(relValue
, relKey
) {
499 model
.setRel(relKey
, relValue
, {silent
: true});
502 setRel: function(key
, value
, options
) {
503 this.rels
= this.rels
|| {};
504 if (this.rels
[key
] != value
) {
505 this.rels
[key
] = value
;
506 this.trigger("rel:" + key
, value
);
509 getRel: function(key
) {
510 return this.rels
? this.rels
[key
] : null;
515 CRM.Backbone.Form = Backbone.Form.extend({
516 validate: function() {
517 // Add support for form-level validators
518 var errors = Backbone.Form.prototype.validate.apply(this, []) || {};
520 if (this.validators) {
521 _.each(this.validators, function(validator) {
522 var modelErrors = validator(this.getValue());
524 // The following if() has been copied-pasted from the parent's
525 // handling of model-validators. They are similar in that the errors are
526 // probably keyed by field names... but not necessarily, so we use _others
529 var isDictionary = _.isObject(modelErrors) && !_.isArray(modelErrors);
531 //If errors are not in object form then just store on the error object
533 errors._others = errors._others || [];
534 errors._others.push(modelErrors);
537 //Merge programmatic errors (requires model.validate() to return an object e.g. { fieldKey: 'error' })
539 _.each(modelErrors, function(val, key) {
540 //Set error on field if there isn't one already
541 if (self.fields[key] && !errors[key]) {
542 self.fields[key].setError(val);
547 //Otherwise add to '_others' key
548 errors._others = errors._others || [];
551 errors._others.push(tmpErr);
559 return _.isEmpty(errors) ? null : errors;
564 // Wrap an optional error callback with a fallback error event.
565 var wrapError = function (model
, options
) {
566 var error
= options
.error
;
567 options
.error = function(resp
) {
568 if (error
) error(model
, resp
, optio
);
569 model
.trigger('error', model
, resp
, options
);
572 })(CRM
.$, CRM
._
, CRM
.BB
);