Custom TreeList that supports query

Author: Alexander Tsvirchkov
Posted: 3/29/2008 7:32:28 AM

Question : I am trying to use query “../../Classified Categories” in the Source for TreeList field of my template. However it seems virtual path is not supported by TreeList field. Is it possible to overcome this problem?

Answer : Tree field supports such kind of queries but TreeList does not for some reason. However, you can easily to overcome this problem by writing a custom TreeList. All we need to “override” one Source property.

Here are steps:

1) Create custom TreeList:

using Sitecore.Data.Items;

using Sitecore.Shell.Applications.ContentEditor;

 

namespace Sitecore.Custom.FieldTypes

{

   public class CustomTreeList : TreeList

   {

 

      public new string Source

      {

         get

         {

            return base.Source;

         }

         set

         {

            if (!value.StartsWith("query:"))

            {

               base.Source = value;

            }

            else

            {

               Item item = Sitecore.Context.ContentDatabase.Items[this.ItemID];

               if (item != null)

               {

                  Item itemQueried = item.Axes.SelectSingleItem(value.Substring("query:".Length));

                  if (itemQueried != null)

                  {

                     base.Source = itemQueried.Paths.FullPath;

                  }

               }

            }

         }

      }

   }

}

 

Compile this class to e.g. CustomDll.

2) Duplicate item
/sitecore/system/Field types/tree list
to
/sitecore/system/Field types/custom tree list

Empty fields and fill these two:
Assembly: CustomDll
Class: Sitecore.Custom.FieldTypes.CustomTreeList

3) Add to a template new “custom tree list” field.

4) Fill the Source with value “query:../../Classified Categories”. Note: query word is obligatory.

5) Enjoy using queries.