This morning, I was fishing around in the core database of my local instance to research my next article — yeah, I know it’s Christmas morning and I should be resting, but unwrapping hidden gems in Sitecore.Kernel beats opening up presents anyday — and discovered that one can easily add his/her own subitems sorting comparer.
After opening up .NET reflector and using Sitecore.Data.Comparers.UpdatedComparer as a model, I created the following Comparer within minutes:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Sitecore.Data.Comparers; using Sitecore.Data.Items; using Sitecore.Diagnostics; namespace Sitecore.Sandbox.Data.Comparers { public class ItemNameLengthComparer : ExtractedKeysComparer { protected override int CompareKeys(IKey keyOne, IKey keyTwo) { Assert.ArgumentNotNull(keyOne, "keyOne"); Assert.ArgumentNotNull(keyTwo, "keyTwo"); return IntegerCompareTo(keyOne.Key, keyTwo.Key); } protected override int DoCompare(Item itemOne, Item itemTwo) { return IntegerCompareTo(itemOne.Name.Length, itemTwo.Name.Length); } private static int IntegerCompareTo(object itemOneNameLength, object itemTwoNameLength) { return IntegerCompareTo((int)itemOneNameLength, (int)itemTwoNameLength); } private static int IntegerCompareTo(int itemOneNameLength, int itemTwoNameLength) { return itemOneNameLength.CompareTo(itemTwoNameLength); } public override IKey ExtractKey(Item item) { Assert.ArgumentNotNull(item, "item"); return new KeyObj { Item = item, Key = item.Name.Length, Sortorder = item.Appearance.Sortorder }; } } }
All we have to do is override and add our own custom logic to the DoCompare(), CompareKeys() and ExtractKey() methods defined in the ExtractedKeysComparer base class.
The above Comparer will sort items based on the length of their names — items with shorter names will appear before their siblings with longer names.
Next, I created a new Child Sorting item in my master database — yes, I did say the master database since I learned the hard way (my sorting option wasn’t appearing) that these sorting comparers are to be defined in each database where they are used — for my Comparer:
Let’s see how this Comparer fares in the wild.
I first created a handful of test items with different item name lengths in a new parent folder under my Home node:
I then opened up the Subitems Sorting dialog and saw my new subitems sorting option in the ‘Sorting’ dropdown:
Nervously, I selected my new subitems sorting option and clicked ‘OK’:
I then wiped my brow and exhaled with relief after seeing that it had worked as I intended:
The above is further evidence of how customizable the Sitecore client truly is. Remember, the Sitecore client was built using the same API/technologies we use each and everyday to build websites within it — thus empowering us to extend the client where we see fit.
Happy Holidays! 🙂