One of the most unknown but very useful feature in Sitecore is the Subitem Sorting. Often there’s a need to sort a group of Items in a particular order. Either to create a good navigation or to help the content editor find their content.
So let’s have a look how this functionality is working. I’ve installed an empty Sitecore 6.1 installation and created a couple of sample items in a random order.
Now I want to sort my items in a less random order. Let’s order them on Display Name. To do so, I’ve to go to my Home and click on the Sorting Command:
A new windows will appear with a list of the default Sitecore Sorting settings:
In this case I select ‘Display Name’. The box below will give me an immediate preview how the new order of the Subitems looks:
There are plenty other options to choose, including Standard Values.
When I click on ‘Ok’, the setting will be applied and my content tree will refresh:
To reflect the change in the front-end, you’ve to publish the Home item including subitems (or execute an Incremental Publish).
Note: As always, it’s a best practice to setup Subitem Sorting on the Standard values of a template. That will make sure that all the items based on the Template will reflect the same sort order. For individual cases, you can set it up on an individual item.
To make sure that this example works fine, I’ve made sure that the name of the item is also inserted in the Title field of my Item:
Now I want to create a custom Sorter which sorts my items rather on Title than on Display Name. The first thing I’ve to do is to write a small class:
1: using Sitecore.Data.Comparers;
2: using Sitecore.Data.Items;
4: public class YetAnotherComparer1 : Comparer
6: protected override int DoCompare(Item item1, Item item2)
8: string x = item1["title"];
9: string y = item2["title"];
11: return x.CompareTo(y);
The class implements Sitecore.Data.Comparers.Comparer. This base class forces you to implement the DoCompare method. Basically, this method reads both title values and compares it using the .NET built-in string.CompareTo().
Note: I’m using the indexer([“fieldname”]) to retrieve fields. This will never return a null, only a string.Empty when the field doesn’t exist or is empty.
Afterwards, we’ve to register the class in Sitecore. We can create an item of the template ‘Child Sorting’ (/sitecore/templates/System/Child Sorting) in /sitecore/system/settings/Subitems Sorting:
Now I’m able to select my item from the sorting dialog:
And from now on, my items will get sorted by title-value.
Of course this is just an example. You can think about different sorters and also use them in the front-end.
Sitecore’s VP and Founder Lars Fløe Nielsen will follow up on this post with more technical details and how to use Sitecore Sorters in the frond-end. I’ll update this post once his second article is published.