Skip to content

Instantly share code, notes, and snippets.

@ethanhxu
Forked from CGaskell/EnumList
Last active September 5, 2017 19:51
Show Gist options
  • Select an option

  • Save ethanhxu/12b3ce25e472e2125f5867c70a55330d to your computer and use it in GitHub Desktop.

Select an option

Save ethanhxu/12b3ce25e472e2125f5867c70a55330d to your computer and use it in GitHub Desktop.
Sitecore Enum Driven Dropdownlist. Uses [Description] attribute if defined.
using System;
using System.ComponentModel;
using Sitecore.Web.UI.HtmlControls;
namespace DetangledDigital.Sc.FieldTypes
{
/*
*
* @CGaskell
* Custom field type. Renders a dropdown list based on a specified enum.
* The code will look for the 'Description' attribute on the enum item and render
* that as the display if it's available. Enum value will be used as dropdown value.
*
* Inspiration from http://www.partechit.nl/en/blog/2013/01/using-an-enumeration-as-data-source
*
*/
public class EnumList : Combobox
{
public string Source { get; set; }
protected override void OnLoad(EventArgs e)
{
if (Controls.Count != 0 || string.IsNullOrWhiteSpace(Source))
return;
try
{
var enumType = Type.GetType(Source);
if (enumType == null) return;
foreach (Enum val in Enum.GetValues(enumType))
{
Controls.Add(new ListItem
{
ID = this.ID + val.ToString(),
Header = GetDescription(val) ?? val.ToString(),
Value = val.ToString()
});
}
}
catch
{
Controls.Add(new ListItem {Header = "Could not load enum for " + Source});
return;
}
base.OnLoad(e);
}
public static string GetDescription(Enum value)
{
var type = value.GetType();
var name = Enum.GetName(type, value);
if (name == null) return null;
var field = type.GetField(name);
if (field == null) return null;
var attr = Attribute.GetCustomAttribute(field, typeof (DescriptionAttribute)) as DescriptionAttribute;
return attr != null
? attr.Description
: null;
}
}
}

Create Field Definition

Create an item of template "Template field type" at "/sitecore/system/Field types/List Types" in core database, you can duplicate "Droplist" but remember to empty the field "Control".

Fill in fields "Assembly" and "Class", in the above code sample's case:

"Assembly": "DetangledDigital"
"Class": "DetangledDigital.Sc.FieldTypes.EnumList"

And that's it. You can now add this field to your template.

Add enum list field to template

In the template builder, add a new field and choose the field type as Enum List, then add the type string of the enum you want to use in the "Source" column of the field. The type string, as standard, is formatted as {Class},{Assembly}, eg. "DetangledDigital.Enum.ColorEnum,DetangledDigital".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment