Created
July 31, 2014 09:48
-
-
Save CGaskell/2b61de0b53b843096ad8 to your computer and use it in GitHub Desktop.
Sitecore Enum Driven Dropdownlist. Uses [Description] attribute if defined.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 = 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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks! This is super helpful.
One improvement suggestion, change the ID of the ListItem to "this.ID + val.ToString()" so that the id is unique. This can prevent error "Field control has failed to render: Multiple controls with the same ID" in "Reset Field Values" form (Content Editor -> Banner "Version" tab -> "Reset" button)