How to apply query in tree list in Sitecore?
Published: 16 October 2023

In Sitecore, if we need some specific kind of datalist selection, we prefer multilist. But we can see just a list of those items, we cannot see its parent node and from where it came as like Treelist.
But in the tree list field, we cannot apply any query as per our requirement. So, let’s do some customization so we can write queries inside the tree list field to take the query-based list in the tree list.
Create one treelistcustom.cs file and inherit the treelist class for getting default controls of treelist in our list and past the below code into that file.
public class TreelistCustom : TreeList { private string dataSource = string.Empty; public override string DataSource { get { if (this.dataSource.StartsWith("query:") && !this.dataSource.Contains("|")) { if (Sitecore.Context.ContentDatabase == null || ItemID == null) { return string.Empty; } var currentItem = Sitecore.Context.ContentDatabase.GetItem(ItemID); Item[] queryResult = null; try { this.dataSource = StringUtil.ExtractParameter("DataSource", Source).Trim(); queryResult = LookupSources.GetItems(currentItem, this.dataSource); } catch (Exception ex) { Log.Error("Treelist field failed to execute query.", ex, this); } if (queryResult == null) { return string.Empty; } return queryResult.FirstOrDefault().Paths.FullPath; } return this.dataSource; } set { this.dataSource = value; } } }
Now, we need to replace the assembly in the tree list from the core database and add the assembly as below.
The path of the item is defined in the below image.

Now we can use any query in the tree list field. For example,
DataSource=query:..&includetemplatesfordisplay=Step,Options&includetemplatesforselection=Options
This is how we can apply a query in the tree list field in Sitecore.

Mitesh Patel - Technical Head - ADDACT
Sitecore || XMCloud || OrderCloud Certified
Mitesh, a distinguished Technical Head at Addact/Addxp, is a prominent figure in Sitecore/XMCloud/OrderCloud certified writing. From Sitecore XM Cloud Developer Certification to Sitecore 10 .NET Developer Certification and Sitecore OrderCloud Certification, Mitesh's expertise is unparalleled. Mitesh is not only a skilled Sitecore CMS developer but also a 12+ years experienced software engineer proficient in various technologies such as MVC, ASP.Net, C#, jQuery, and Azure cloud/AWS.