Sitecore Source Field Code: query that implements IDataSource

Image

I came across something cool today! When a CheckList, MultiList, TreeList, or etc. field are on your template, they eventually call into the Sitecore.Web.UI.HtmlControls.Data.LookupSources.GetItems() class and method. This calls the getLookupSourceItems pipline. This pipeline contains the following processor:[code language="xml"]<getLookupSourceItems> <processor type="Sitecore.Buckets.FieldTypes.CustomDataSource, Sitecore.Buckets" patch:source="Sitecore.Buckets.config"/></getLookupSourceItems>[/code]If we take a look at Sitecore.Buckets.FieldTypes.CustomDataSource in Sitecore.Buckets.dll, we can see that this class will allow us to prefix our source field with "code:" and then add a type and assembly that implements Sitecore.Buckets.FieldTypes.IDataSource to return a list of items.Lets take a look at an example. I've created a class that implements IDataSource:[code language="csharp"]using Sitecore.Buckets.FieldTypes;using Sitecore.Data.Items;namespace Hi.Sc.Buckets{ public class CustomDataSource : IDataSource { public Item[] ListQuery(Item item) { string homePath = "/sitecore/content/home"; Item homeItem = Sitecore.Context.ContentDatabase.GetItem(homePath); if (homeItem != null) { return homeItem.GetChildren().ToArray(); } return new Item[0]; } }}[/code]You'll need to include Sitecore.Buckets.dll as a reference in your project. Next add a field to an existing template:[caption id="attachment_1009" align="alignnone" width="780"]

add field with code

add field with code[/caption]I've added the following line to my source field of my MultiList where Hi.Sc.Buckets.CustomDataSource is my class that implements Sitecore.Buckets.FieldTypes.IDataSource and Hi.Sc is the name of my dll:[code language="csharp"]code:Hi.Sc.Buckets.CustomDataSource, Hi.Sc[/code]When I take a look at my MultiList, you can see it is pulling the children of the home item:[caption id="attachment_1010" align="alignnone" width="780"]

multilist working with code in source field

multilist working with code in source field[/caption]This can be expanded upon to create some really cool lists of items and I think we can all agree that it is easier to write C# code than Sitecore Query.