Monday, March 17, 2008

Sorting Content Items

By default, Sitecore sorts content items based on their sortorder attribute. Sortorder describes how a single content item should be sorted relative to its siblings. (If the sortorder attribute is not set, Sitecore uses the SubItems Sorting value of the parent item. See here for more information: http://sdn5.sitecore.net/Scrapbook/Understanding%20the%20Sort%20Order.aspx.) To set the sort order of an item, business users can click on the sort commands in the ribbon. The sort commands provide commonly required options:



Clicking on one of these commands updates the sortorder attribute of the selected content item:


Clicking on the sorting options allows business users to sort the subitems of the current item based on a number of criteria:



Rendering logic will implicitly recognize this sort order, such that the following rendering will respect the sortorder field:

    <xsl:for-each select="$home/item[@key='vehicles']/item">
      <sc:link>
        <sc:image field="menu image" />
        <sc:text field="menu title" />
        </sc:link>
    </xsl:for-each>

Sitecore allows developers to implement their own sorting algorithms (http://sdn5.sitecore.net/Scrapbook/Understanding%20the%20Sort%20Order.aspx). Algorithms can be specified under /sitecore/system/settings/subitems sorting. For example, to sort items by a date field, developers can use the following approach:

public class ItemComparer : IComparer
{
private string _fieldName;

public ItemComparer()
{
}

public ItemComparer(string fieldName)
{
_fieldName = fieldName;
}

public int Compare(object x, object y)
{
Item item1 = x as Item;
Item item2 = y as Item;

if (_fieldName == null)
{
_fieldName = "date";
}

Sitecore.Data.Fields.DateField date1 = (Sitecore.Data.Fields.DateField)item1.Fields[_fieldName];
Sitecore.Data.Fields.DateField date2 = (Sitecore.Data.Fields.DateField)item2.Fields[_fieldName];
return System.DateTime.Compare(date1.DateTime,
date2.DateTime);
}
}

This class can be used in your code-behind as follows:

// get an array of the Items:

Item[] i = Sitecore.Context.Database.SelectItems("");

// sort it using your comparer:

Array.Sort(i, new ItemComparer());

// use the sorted array:

foreach (Sitecore.Data.Items.Item thisItem in i) {
// do something with each item
}

No comments: