Progressively Build up my CAML

Oct 9, 2015 at 4:58 PM
So, I have 4 multi-select dropdown boxes on my page where users can choose filter options...

I'll need to build up some complex CAML from these for my list item selector, but I need to progressively build it up.

For example, if dropdown box 1 has selections, then add a Where Clause ,and if there are more than one selected, OR them.

Same with dropdown 2... but then we need to AND the different dropdown boxed, etc. i.e:

(dd1op1 OR dd1op2 OR dd1op5) AND (dd2op2 OR dd2op3) AND (dd3op6)

Can I do this programmatically? Once I have created my CAML using the builder I can't see how to add new clauses in. There is the ModifyAdd.. but I am starting from no Where items (just a view with a row limit) but want to push the Where clauses in as appropriate.

I hope that makes sense and isn't too confusing.
Oct 9, 2015 at 7:01 PM
Edited Oct 10, 2015 at 11:09 AM

If I got you right, it's just a nested dynamic query. This can be solved with CamlBuilder.Expression.

Let's say you prepared arrays with values:
var dd1_values = ['dd1op1','dd1op2'];
var dd2_values = ['dd2op1'];
var dd3_values = ['dd3op1','dd3op2','dd3op3','dd3op4'];
Then you can build expressions from those values, like this:
var dd1_expr_array = [];
for (var i=0;i<dd1_values.length;i++)
  dd1_expr_array.push( CamlBuilder.Expression().TextField("Category1").EqualTo(dd1_values[i]) );
And so forth for all drop downs.

Now let's join them:
var all_expr_array = [];
if (dd1_expr_array.length>0)
if (dd2_expr_array.length>0)
if (dd3_expr_array.length>0)
Then, form the final query:
var query = new CamlBuilder().Where().All(all_expr_array).ToString();
Something like this.

P.S. Of course, if your values are integers (i.e. IDs), then you'd better use In operator, like this:
var dd1_expr = CamlBuilder.Expression().TextField("Category1").In(dd1_values[i]);
Marked as answer by MarkStokes on 10/12/2015 at 9:41 AM
Oct 12, 2015 at 5:42 PM

Thank you so much. This works like a dream,

Please keep up the good work with this tool. It just saved me a ton of time.
Apr 14, 2016 at 9:48 PM
This example from Omlin is what I needed. I think if I had not seen this discussion I would have given up on this tool. I think this example should be put in on the home page.