How do you support selecting multiple enum values for an EPiServer property?

1.8k views Asked by At

I have a property which allows a user to select multiple enum values, and at the moment this works fine for saving the information into the database and for using it. However it doesn't seem to correctly read the values out of the property back to the edit UI.

I presume there is some sort of type issue with the enum which causes the SelectMany values not to be set as you'd expect.

I have the following enum:

public enum Skills
{
    People,
    IT,
    Management,
    Sales,
}

And the following ISelectionFactory:

using System;
using System.Collections.Generic;
using System.Linq;

namespace TestSite.Business.EditorDescriptors
{
    using EPiServer.Shell.ObjectEditing;

    public class EnumSelectionFactory<TEnum> : ISelectionFactory
    {
        public IEnumerable<ISelectItem> GetSelections(ExtendedMetadata metadata)
        {
            var values = Enum.GetValues(typeof(TEnum));

            return (from object value in values select new SelectItem { Text = this.GetValueName(value), Value = value }).OrderBy(x => x.Text);
        }

        private string GetValueName(object value)
        {
            return value.ToString();
        }
    }
}

Then I have the property which I've added to the ContactPage model in the Alloy Demo.

    [SelectMany(SelectionFactoryType = typeof(EnumSelectionFactory<Skills>))]
    public virtual string EmployeeLevels { get; set; }

Does anyone know how to solve this?

2

There are 2 answers

0
WarnoX On BEST ANSWER

Set the underlying value type ...

namespace TestSite.Business.EditorDescriptors
{
    using EPiServer.Shell.ObjectEditing;

    public class EnumSelectionFactory<TEnum, TUnderlying> : ISelectionFactory
    {
        public IEnumerable<ISelectItem> GetSelections(ExtendedMetadata metadata)
        {
            var values = Enum.GetValues(typeof(TEnum));

            return (from TEnum value in values select new SelectItem { Text = this.GetValueName(value), Value = Convert.ChangeType(value, typeof(TUnderlying)) }).OrderBy(x => x.Text);
        }

        private string GetValueName(object value)
        {
            return Enum.GetName(typeof(TEnum), value);
        }
    }
} 

...implemented by your model with a string type ...

[SelectMany(SelectionFactoryType = typeof(EnumSelectionFactory<Skills,string>))]
public virtual string EmployeeLevels { get; set; } 
1
Johan Petersson On

Seems to be a bug. Please report to EPiServer.