Create a custom sorting routine for content
How to Implement a Custom Child Sorting Rule
Sitecore provides a number of out-of-the-box sorting rules that can be implemented throughout your solution. Some of these include:
- Created By
- Display Name
If you need to apply your own custom logic to child items, Sitecore enables developers to quickly build custom sorting rules.
- Create a custom comparer source code file using Sitecore Rocks
- New Item... >> Sitecore > UI > Subitems Sorting Comparer
- Modify to meet your sorting requirements
- Examples code below sorts based on common "Title" field
- namespace Sitecore.Starterkit
- using Sitecore.Data.Comparers;
- using Sitecore.Data.Items;
- public class TitleComparer : Comparer
- protected override int DoCompare(Item item1, Item item2)
- string title1 = item1["Title"];
- string title2 = item2["Title"];
- if ((title1.Length > 0) && (title2.Length > 0))
- if ((title1 == '_') && (title2 != '_'))
- return 1;
- if ((title2 == '_') && (title1 != '_'))
- return -1;
- return title1.CompareTo(title2);
- In the Content Editor, select the /Sitecore/System/Settings/Subitems Sorting item
- In the Content Editor, insert a child sorting rule definition item using the /System/Child Sorting data template. For the name of the item, use the name of the custom item comparer class or the name of the property by which the custom item comparer sorts
- In the Content Editor, select the newly created child sorting rule definition item
- In the Content Editor, in the new child sorting rule definition item, in the Data section, in the Type field, enter the signature of the custom item comparer class. See example below from a project called Starterkit.
- Save your changes and you'll be ready to test and use your new Sorting Rule
- To implement, select and item of which child items you want to sort using your sorting rule. If you haven't done so already, show Standard Fields (View tab >> Standard Fields). Go to the Appearance field section and select your custom sorting rule in the Child Sorting rule field.
NOTE: Keep in mind that the Sortorder field (In Appearance field section) is going to overrule any child sorting rules. Set values to null for child sorting to take effect.