How to Generate a Completely Dynamic List of Data For Any Item Field Anywhere in the Tree Using Sitecore Query

How's that for a title?

Here we are again, trying to limit field selection via the field’s source using Sitecore Query. Generating any dynamic list of items becomes pretty simple once you work with Sitecore Query a few times.

In a related article, we covered how to create a dynamic multilist of item children using the Sitecore Query. This is very useful for dynamically defining the source of any field type that supports multiple item selection.

The code was fairly simple:


query:.//*[@@templatename='News Article']

The query gets the current item in the tree and finds all descendants of that item with the template name of "News Article".

But now let's try to do something a little more complex that requires us to go up the tree and then back down again. Let's say that you own a club that puts on events. Your club has official branch locations, and events can be at none, one, or many of those branches. To make it even more complex, let's say that in your sitecore project, it's possible that there could be 'n' number of clubs. So, the big challenge is that for any club who is logged in and looking to add events, they should only be able to select branch locations for an event that belong to their club.

The structure of your tree might differ slightly, but here is what you would put in the source of your Event item field called "Branch List", whether it's a checklist or multilist, and so on:


query:.//ancestor::*[@@templatename='Club']//*[@@templatename='Branches']//*[@@templatename='Branch']

What this query does is given an Event item, move up the tree to find its ancestor that is a Club template. Then, drill back down into the tree for a Branches template item (if this is a folder, just create a folder template). Finally, get all children of that Branches item with a template name of Branch.

With this information, you should be able to do pretty much anything you would ever need to with regards to generating dynamic lists of items for use in multi select type fields.

Happy coding!

Marcel

Fish