How to Alphabetize the Selected List of a Field in Sitecore

This is a continuation of my previous blog post, in which explained how to remove Sitecore list field icons (up/down, etc). The project I was working on was a two-part request, and this post will explain the first part and how it was handled.

Client wanted a field on their item to be sorted alphabetically (technically the Selected list of that field). This is best handled by creating a new TreeList field that will inherit from TreeList. Or, if you are using MultiList or some other list type, that should work fine as well. Let’s get started.

  1. The first thing you will need to do is create a new class for your custom list field. Ideally you would place this in the Fields folder of your project, if you have one. Edit the class so that it inherits from the appropriate base class, i.e. TreeList.
  2. Then, create a new custom field in Sitecore and publish it. For instructions on how to do that, see my previous blog (link here). In fact, if you already went through the instructions of that post, this is already done.
  3. Going back to your class created in Step 1, you’ll want to override the OnLoad() event and add in the logic to alphabetize. My method was (pseudo code):
    1. Get the current list of guids in the field.
    2. Convert each to an item and add it to a generic list.
    3. Use a generic OrderBy() to sort the list by item display name.
    4. Build a string of pipe-delimited, guids from the sorted list, and set the list field’s value to that.

The result was the following code:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using Sitecore;
using Sitecore.Configuration;
using Sitecore.Data;
using Sitecore.Data.Fields;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.Globalization;
using Sitecore.Resources;
using Sitecore.SecurityModel;
using Sitecore.Shell.Applications.ContentEditor;
using Sitecore.Web.UI.HtmlControls;
using Sitecore.Web.UI.Sheer;
using Sitecore.Web.UI.WebControls;

namespace your.namespace.here
{
    public class AlphaTreeList : TreeList
    {
        protected override void OnLoad(EventArgs args)
        {
            if (!string.IsNullOrEmpty(base.ItemID))
            {
                SortAssociatedProductsAlpha(Sitecore.Context.ContentDatabase.GetItem(base.ItemID));
            }

            base.OnLoad(args);
        }

        private void SortAssociatedProductsAlpha(Item i)
        {
            using (new SecurityDisabler())
            {
                var associatedProducts = i.Fields["Associated Products"];
                var alphaGuids = GetAlphabetizedGuidString(i, associatedProducts);

                if (alphaGuids.Equals(associatedProducts.Value)) return;

                if (alphaGuids != string.Empty)
                {
                    using (new EditContext(i))
                    {
                        this.Value = alphaGuids;
                    }
                }
            }
        }

        private string GetAlphabetizedGuidString(Item i, Field f)
        {
            List<Item> items = new List<Item>();
            StringBuilder scGuidBuilder = new StringBuilder();

            if (i != null && f != null)
            {
                foreach (ID guid in ((MultilistField)f).TargetIDs)
                {
                    Item target = Sitecore.Data.Database.GetDatabase("master").Items.GetItem(guid);
                    items.Add(target);
                }

                // Sort it by item name.
                items = items.OrderBy(o => o.DisplayName, StringComparer.OrdinalIgnoreCase).ToList();

                // Build a string of pipe-delimited guids.
                foreach (Item item in items)
                {
                    scGuidBuilder.Append(item.ID);
                    scGuidBuilder.Append("|");
                }

                // Return string which is a list of guids. And remove that last pipe.
                return scGuidBuilder.ToString().TrimEnd('|');
            }

            return string.Empty;
        }
    }
}

Lastly, you should change the field type for this field in your environment to your new custom field type.

This should work every time you open the item or add a new item to the field’s Selected list and save.

Advertisements

One thought on “How to Alphabetize the Selected List of a Field in Sitecore

  1. Hi Everyone,

    I made an edit to this blog post, after discovering that the code wasn’t working 100% of the time. Specifically, the orderby() function would sometimes process certain strings out of order. So I just replaced:

    items = items.OrderBy(o => o.DisplayName).ToList();

    with:

    items = items.OrderBy(o => o.DisplayName, StringComparer.OrdinalIgnoreCase).ToList();

    And that fixed the sorting issues.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s