How to sort the list of sites in the Create Sites page

In a customer deployment, we had several custom Site Definitions to create (because they have variations) and we started noticing that the list of sites available in the Create Page is sorted in an odd way.  In fact, it's using neither the creation order, the configuration ID, nor the title (which is okay since it's multilingual).

Using Reflector, I noticed that the page was using the GetAvailableWebTemplates() method of the SPWeb class in order to get its list.  I tried sorting the list like I wanted and then using the SetAvailableWebTemplate() but the list was still being returned in the original sorted way.

Digging deeper with Reflector, I noticed that it uses the web property "__WebTemplates" and that returns a list of 'All' web templates as well as web templates by LCID.

Here's the method I created to sort the web's site creation list.  You need to pass an SPWeb, a flag to determine if you want to be recursive, and the LCID of your web.  In my case, I only had All + 1033 in the English, and All + 1036 in French.  If you have multiple languages available in the same site, you may need to update the code a little bit.

    1: private void SortWebTemplates(SPWeb web, bool recursive, uint lcid)
    2: {
    3:     SPWebTemplateCollection webTemplates = web.GetAvailableWebTemplates(lcid);
    4:     StringBuilder sb = new StringBuilder();
    5:  
    6:     Collection<SPWebTemplate> collection = new Collection<SPWebTemplate>();
    7:     foreach (SPWebTemplate template in webTemplates)
    8:     {
    9:         bool itemAdded = false;
   10:  
   11:         for (int i = 0; i < collection.Count; i++)
   12:         {
   13:             if (template.Title.CompareTo(collection[i].Title) < 0)
   14:             {
   15:                 collection.Insert(i, template);
   16:                 itemAdded = true;
   17:                 break;
   18:             }
   19:         }
   20:  
   21:         if (!itemAdded)
   22:             collection.Add(template);
   23:     }
   24:  
   25:     sb.Append("<webtemplates><lcid id=\"all\">");
   26:     foreach (SPWebTemplate webTemplate in collection)
   27:     {
   28:         sb.Append("<webtemplate name=\"" + webTemplate.Name + "\" />");
   29:     }
   30:     sb.Append("</lcid><lcid id=\"" + lcid.ToString() + "\">");
   31:     foreach (SPWebTemplate webTemplate in collection)
   32:     {
   33:         sb.Append("<webtemplate name=\"" + webTemplate.Name + "\" />");
   34:     }
   35:     sb.Append("</lcid></webtemplates>");
   36:  
   37:     web.AllProperties["__WebTemplates"] = sb.ToString();
   38:     web.Update();
   39:  
   40:     if (recursive && web.Webs.Count > 0)
   41:     {
   42:         foreach (SPWeb subWeb in web.Webs)
   43:         {
   44:             SortWebTemplates(subWeb, recursive, lcid);
   45:             subWeb.Dispose();
   46:         }
   47:     }
   48: }

 

Maxime