Sitecore languages sorting by code

I have to write a component which will show a list of languages configured in Sitecore a drop-down menu. But there is a special requirement that the languages should be sorted by the administrator in any order under the content tree and the drop-down must render the languages in the same order.

In Sitecore, there is no API that gives us a way to get languages in sorted order based on Sortorder field.

So, I tried to google it and found the following article, which provided some idea about how to enable sorting of languages in Content Editor.

Sitecore 8.1 Language Dropdown Sorting in Content Editor

However, my requirements are different and I want to develop a component which lists the languages in sorted order. Based on the above language, I got inspiration to refactor the Sitecore assembly to see how they have implemented the LanguageManager. After studying few assemblies I got an idea and came up with a solution.

Following code snippet is the extension method to get the languages in sorted order based on the Sortorder field:

public static ICollection<Language> GetLanguages(this Item item)
{
  var versions = new List<Language>();
  var database = item.Database;
  var items = database.SelectItems("fast://*[@@templateid='{0}']".FormatWith(new object[] { TemplateIDs.Language })).OrderBy(x => x[FieldIDs.Sortorder]);
  foreach(var languageItem in items)
  {
    var language = LanguageManager.GetLanguage(languageItem.Name);
    if(language != null)
    {
      var versionedItem = database.GetItem(item.ID, language);
      versions.AddRange(versionedItem.Versions.GetVersions().Select(v => v.Language));
    }
  }
  return versions;
}

Use this method to get a list of languages for a particular item and in sorted order based on Sortorder field.

However, to make this working you need to Unprotect the language items under /Sitecore/System/Languages and set the Sortorder field value or sort the items in the content tree.

Hope this help you and save you time which I’ve to spend on finding this solution.

Leave a Reply