Sitecore Source Field Code: query that implements IDataSource

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:

<getLookupSourceItems>
    <processor type="Sitecore.Buckets.FieldTypes.CustomDataSource, Sitecore.Buckets" patch:source="Sitecore.Buckets.config"/>
</getLookupSourceItems>

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:

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];
        }
    }
}

You’ll need to include Sitecore.Buckets.dll as a reference in your project. Next add a field to an existing template:

add field with code
add field with code

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:Hi.Sc.Buckets.CustomDataSource, Hi.Sc

When I take a look at my MultiList, you can see it is pulling the children of the home item:

multilist working with code in source field
multilist working with code in source field

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.

2 thoughts on “Sitecore Source Field Code: query that implements IDataSource

Add yours

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: