Santa

Let’s Talk

We would love to hear from you. Want to know more about
our services or have any questions? Say Hi!

How to apply query in tree list in Sitecore?

October 16, 2023
How to apply query in tree list in Sitecore?
Juanita Xavier
Juanita Xavier
Technical Head
how-to-apply-query-in-tree-list-in-sitecore

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.

how-to-apply-query-in-tree-list-in-sitecore-1

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.


YOU MAY ALSO LIKE