Using an enumeration as data source

04 januari 2013 om 00:00 by Ruud van Falier - Post a comment

I've created a new field type that allows you to set a C# enumeration as data source for a DropList field control.
To set this up, follow these instructions:

First you switch to the Core database and open the Content Editor.
In there you add a new field type to /sitecore/system/Field types/List Types, calling it EnumList.
See the screenshot for all details.

Now create the C# class for the field type, in my example it's called EnumList.cs

using System;
using Sitecore.Web.UI.HtmlControls;

namespace ParTech.Demo.FieldTypes
{
    public class EnumList : Combobox
    {
        public string Source { get; set; }

        protected override void OnLoad(EventArgs e)
        {
            if (Controls.Count == 0)
            {
                try
                {
                    Type enumType = Type.GetType(Source);
                    string[] enumValues = Enum.GetNames(enumType);

                    foreach (string v in enumValues)
                    {
                        Controls.Add(new ListItem
                        {
                            ID = v,
                            Header = v,
                            Value = v
                        });
                    }
                }
                catch (Exception)
                {
                    Controls.Add(new ListItem
                    {
                        Header = "Could not load enumeration"
                    });
                }
            }

            base.OnLoad(e);
        }
    }
}

And create an example enumeration:

namespace ParTech.Demo.Enums
{
    public enum Animals
    {
        Cat,
        Dog,
        Horse,
        Pig,
        Cow,
        Bird,
        Chicken
    }
}

Now we can start using our new field type!
Add it to one of your templates, like I did in this example:

The Source field must be set to the fully qualified name of your enumeration.
So in my example this is "ParTech.Demo.Enums.Animals, ParTech.Demo" (the assembly name may be omitted in this case).

If you take a look at the result now, you will see a DropList control with the values from your enumeration.