X-Git-Url: https://vcs.fsf.org/?a=blobdiff_plain;f=js%2Fcrm.backbone.js;h=2e2e381fe82804720dde8c7b939c8673fb91edaf;hb=27e0bdba223bf18398c1229f3994fa77fc58f66e;hp=e84089476cd93790e140ea0debaf7eeafb345c71;hpb=e8b1bc2ad9d2ff8c901e21be4cb01bb7e0958e69;p=civicrm-core.git diff --git a/js/crm.backbone.js b/js/crm.backbone.js index e84089476c..2e2e381fe8 100644 --- a/js/crm.backbone.js +++ b/js/crm.backbone.js @@ -161,6 +161,45 @@ }); }; + /** + * Find a single record, or create a new record. + * + * @param Object options: + * - CollectionClass: class + * - crmCriteria: Object values to search/default on + * - defaults: Object values to put on newly created model (if needed) + * - success: function(model) + * - error: function(collection, error) + */ + CRM.Backbone.findCreate = function(options) { + options || (options = {}); + var collection = new options.CollectionClass([], { + crmCriteria: options.crmCriteria + }); + collection.fetch({ + success: function(collection) { + if (collection.length == 0) { + var attrs = _.extend({}, collection.crmCriteria, options.defaults || {}); + var model = collection._prepareModel(attrs, options); + options.success(model); + } else if (collection.length == 1) { + options.success(collection.first()); + } else { + options.error(collection, { + is_error: 1, + error_message: 'Too many matches' + }); + } + }, + error: function(collection, errorData) { + if (options.error) { + options.error(collection, errorData); + } + } + }); + }; + + CRM.Backbone.Model = Backbone.Model.extend({ /** * Return JSON version of model -- but only include fields that are