Handling Sitecore Items

There are times when you want to manipulate an item that is passed into a method rather than one you have loaded yourself from the Sitecore database, two good example of this are when you are working with the Sitecore workflow and pipelines.

In this tutorial we will create a routine to sort the the events we created in the last tutorial. The current order of our event items are shown below:

These items are sorted randomly at the moment but to make it easier for our content team to find events we are going to sort them by Start date. Our comparer logic is very straight forward:

using Glass.Mapper.Sc;
using Glass.Mapper.Sites.Sc.Models.Content;
using Sitecore.Data.Comparers;

namespace Glass.Mapper.Sites.Sc.Client.Item
    public class EventSortOrder : DefaultComparer
        protected override int DoCompare(Sitecore.Data.Items.Item item1, Sitecore.Data.Items.Item item2)
            if (item1.TemplateName == "Event")
                var evnt1 = item1.GlassCast<Event>();
                var evnt2 = item2.GlassCast<Event>();

                return evnt1.Start.CompareTo(evnt2.Start);

            return base.DoCompare(item1, item2);

The GlassCast method allows you to convert a Sitecore item to a specific type loaded by the default Glass.Mapper context. Data is read directly from the item avoiding any unnecessary calls to the Sitecore data layer. It also has a matching extension method called GlassRead that allows you to read properties from a class back onto the item.

Now that we have our sort method we just need to create the compare item in Sitecore:

Finally we just need to update the Subitems Sorting field on the standard values field of our Events Folder template:

Now if we look at the order of our events we can see that they have reorganised themselves into the correct order:

In this tutorial you have seen how you can convert an item into a strongly typed object without having to request it from the Sitecore database allowing you to use Glass.Mapper almost anywhere!