Monday, September 23, 2013

Lighting the Batsignal

A while ago, I tweeted that Dan Solovay had asked me a question about Sitecore, and that I had the answer. Because Dan can't be the only one with this question, I figured I should post the question and answer here.

The question had to do with item sorting. By default, when you insert a new item, Sitecore will sort it alphabetically among the existing siblings. You can then move the item up or down in the content editor (via the sorting options or the super cool keyboard shortcut, ctrl + shift + alt + up/down).

There is another option built into Sitecore for sorting items. You can configure Sitecore to show the items in date order (which is what Dan wanted). However, when you enable this option, you lose the ability to manually override the sorting (which is not what Dan wanted).

And thus, the Sitecore MVP came to me, using the call normally reserved for either trouble in Gotham City or help needed from a Sitecore MVP.

My suggestion was to add a processor to the item:added pipeline and, in that processor, adjust the sort order field on the items. It's more work than a configuration change, but it definitely would work.

I threw together some sample code that would just make sure the new item is added at the top of the item list:

public class EditSort_ItemAdded
{
  public void OnItemAdded(object sender, EventArgs args)
  {
    if (args == null)
      return;
    var item = Event.ExtractParameter(args, 0) as Item;
    if (item == null)
      return;

    SetSortOrder(item);
  }

  protected void SetSortOrder(Item newItem)
  {
    var parent = newItem.Parent;

    var children = parent.Children.ToList();

    int minSort = Convert.ToInt32(children.Min(c => c.Appearance.Sortorder));

    using (new Sitecore.SecurityModel.SecurityDisabler())
    {
      newItem.Editing.BeginEdit();
      newItem.Appearance.Sortorder = minSort - 10;
      newItem.Editing.AcceptChanges(false, true);
    }
  }
}

So that's it. Certainly not an epic save, and I'm not sure it's the best answer, but it made my day nonetheless.

No comments:

All rights reserved. Take that!