Created
March 23, 2012 12:14
-
-
Save cajones/2170140 to your computer and use it in GitHub Desktop.
Caml Query Builder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var CamlQueryBuilder = function() { | |
}; | |
CamlQueryBuilder.prototype.withExactValues = function(fieldValues) { | |
this.exactFieldValues = fieldValues; | |
this.doExactQuery = true; | |
}; | |
CamlQueryBuilder.prototype.thatContains = function(fields, values) { | |
this.containsFields = fields; | |
this.containsValues = values; | |
this.doContainsQuery = true; | |
}; | |
CamlQueryBuilder.prototype.build = function() { | |
var self = this; | |
var caml = ''; | |
if(!self.doExactQuery && !self.doContainsQuery) return ''; | |
caml = "<Query><Where>"; | |
if(self.doExactQuery && self.doContainsQuery) { | |
caml += "<And>"; | |
} | |
if(self.doExactQuery) { | |
if (self.exactFieldValues === undefined || self.exactFieldValues.length === 0) return ''; | |
if (self.exactFieldValues.length > 1) { | |
caml += "<And>"; | |
} | |
$.each(self.exactFieldValues, function (i, e) { | |
caml += '<Eq><FieldRef Name="' + e.id + '" /><Value Type="Text">' + e.value + '</Value></Eq>'; | |
}); | |
if (self.exactFieldValues.length > 1) { | |
caml += "</And>"; | |
} | |
} | |
if(self.doContainsQuery) { | |
if (self.containsFields.length > 1 || self.containsValues.length > 1) { | |
caml += "<Or>"; | |
} | |
$.each(self.containsFields, function (i, field) { | |
$.each(self.containsValues, function (i, value) { | |
caml += '<Contains><FieldRef Name="' + field + '" /><Value Type="Text">' + value + '</Value></Contains>'; | |
}); | |
}); | |
if (self.containsFields.length > 1 || self.containsValues.length > 1) { | |
caml += "</Or>"; | |
} | |
} | |
if(self.doExactQuery && self.doContainsQuery) { | |
caml += "</And>"; | |
} | |
caml += "</Where></Query>"; | |
return caml; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment