Linus Ekström
May 6, 2014
  14838
(8 votes)

Enum properties for EPiServer 7.5

Joel Abrahamsson wrote a nice blog post about how to define a property that uses an enum that gives the editor a selection of choices in the UI. This code was written for EPiServer 7 and there are some changes in EPiServer 7.5 that makes it possible to do some small improvements to this pattern. So here is a EPiServer 7.5 version for the same use case.

First, lets start with just copying the selection factory from the original blog post:

using System;
using System.Collections.Generic;
using EPiServer.Framework.Localization;
using EPiServer.Shell.ObjectEditing;
 
namespace EPiServer.Samples
{
    public class EnumSelectionFactory<TEnum> : ISelectionFactory
    {
        public IEnumerable<ISelectItem> GetSelections(
            ExtendedMetadata metadata)
        {
            var values = Enum.GetValues(typeof(TEnum));
            foreach (var value in values)
            {
                yield return new SelectItem
                {
                    Text = GetValueName(value),
                    Value = value
                };
            }
        }
 
        private string GetValueName(object value)
        {
            var staticName = Enum.GetName(typeof(TEnum), value);
 
            string localizationPath = string.Format(
                "/property/enum/{0}/{1}",
                typeof(TEnum).Name.ToLowerInvariant(),
                staticName.ToLowerInvariant());
 
            string localizedName;
            if (LocalizationService.Current.TryGetString(
                localizationPath,
                out localizedName))
            {
                return localizedName;
            }
 
            return staticName;
        }
    }
}

 

The difference with the original approach is that we want to use attributes that are using the IMetadataAware interface. This is an interface defined in System.Web.MVC that makes it possible to modify the metadata used for editing from an attribute and EPiServer 7.5 supports the usage of this. We will inherit from SelectOneAttribute, that handles definition of the editor to be used and just provide this with the correct selection factory instance for the given enum:

using System;
using System.Web.Mvc;
using EPiServer.Shell.ObjectEditing;
 
namespace EPiServer.Samples
{
    public class EnumAttribute : SelectOneAttribute, IMetadataAware
    {
        public EnumAttribute(Type enumType)
        {
            EnumType = enumType;
        }
 
        public Type EnumType { get; set; }
 
        public new void OnMetadataCreated(ModelMetadata metadata)
        {
            var enumType = metadata.ModelType;
 
            SelectionFactoryType = typeof(EnumSelectionFactory<>).MakeGenericType(EnumType);
 
            base.OnMetadataCreated(metadata);
        }
    }
}

 

And the usage in your models would look like this:

[BackingType(typeof(PropertyNumber))]
[EnumAttribute(typeof(Priority))]
public virtual Priority Priority { get; set; }

Note 1: The need to define the backingtype attribute for enums is fixed in EPiServer.CMS 8.1.

Note 2: You could argue that you should be able to resolve the enum type from the type of the property in the OnMetadataCreated method. That would work in plain MVC but unfortunately this information is lost in the changes done to support properties that does not have a model (ie, non-typed models).

 

The result is a drop down with the potentially localized enum values, just as in the original blog post:

1972_2306

May 06, 2014

Comments

pevi
pevi May 8, 2014 10:30 AM

test

May 8, 2014 10:40 AM

Sweet! Me like...

May 12, 2014 03:08 PM

Good post!

Martin Emanuelsson
Martin Emanuelsson Sep 3, 2014 01:43 PM

Hello,

I've tried to implement this solution but get an error message saying the following when selecting a value in my drop down based on an Enum:

Unexpected token parsing date. Expected Integer or Float, got String.

Is this something that anyone of you have come across before and have a solution for?

/Martin

Sep 3, 2014 01:58 PM

No, not that I've heard about. Do you have repro steps and/or code to reproduce this?

Martin Emanuelsson
Martin Emanuelsson Sep 3, 2014 04:21 PM

Of course the problem was created on our side. I just realized that we had done changes to the EnumSelectionFactory to use the Enum DisplayAttribute as a source for the value to be shown to the editor, instead of using resource files as in Joel's example, and that solution had a bug in it which we easily solved. Thanks for your quick response and sorry about bothering you :-)

Martin Emanuelsson
Martin Emanuelsson Sep 3, 2014 05:12 PM

While I'm already bothering you :-) Do you have a suggestion for how to make this work also for a SelectManyAttribute based on an enum and have the model return a list of enums or a bitwise enum? I've gotten everything to work except for the model returning enum(s).

Niklas Wanngren
Niklas Wanngren Oct 15, 2014 02:10 PM

I have a question regarding translations. If I add the enum property to a view (preview) with @Html.Properyfor(m=>m.enum) the text in the dropdown will be the value of the currently selected enum. However when I click the property to change the list that extends to the right will be correctly translated.

For example I have a enum with values "Color1" and "Color2". These are translated to "Blue" and "Green". In the normal cms view it will display "Color1" but if I click to change it the dropdown I get from the right will correctly display "Blue" and "Green".

Is there any solution to this?

Jan 27, 2015 02:51 PM

@Martin and others, seems like someone wrote a select many editor with enum values: http://world.episerver.com/blogs/russell-mercer/dates/2015/1/post-title/

Brad McDavid
Brad McDavid Feb 2, 2015 04:33 PM

This doesn't seem to work for EPiServer.CMS.Core version 7.19.2. I'm getting the following error after building: The backing type 'SocialMediaType' attributed to the property 'LinkType' on 'SocialLinkData' does not inherit PropertyData, where 'SocialMediaType' is an enum. I also tried removing the backing type attribute for the enum and get: Type 'SocialMediaType' could not be mapped to a PropertyDefinitionType.

Is there a new way to accomplish this functionality?

Feb 10, 2015 01:36 PM

Hi Brad!

I'm not sure what the SocialMediaType you are referring to is. If you have a custom property you need to make sure that the PropertyDataType property returns the same type as you are using for your value type on your content model.

Brad McDavid
Brad McDavid Feb 13, 2015 11:26 PM

Hi Linus,

I realize my issue now was setting the backing type of [BackingType(typeof(SocialMediaType))] where SocialMediaType was an enum, changing the backing type to [BackingType(typeof(PropertyNumber))] resolved it.

Thanks,
Brad

Please login to comment.
Latest blogs
Optimizely Forms: You cannot submit this form because an administrator has turned off data storage.

Do not let this error message scare you, the solution is quite simple!

Tomas Hensrud Gulla | Oct 4, 2024 | Syndicated blog

Add your own tools to the Optimizely CMS 12 admin menu

The menus in Optimizely CMS can be extended using a MenuProvider, and using the path parameter you decide what menu you want to add additional menu...

Tomas Hensrud Gulla | Oct 3, 2024 | Syndicated blog

Integrating Optimizely DAM with Your Website

This article is the second in a series about integrating Optimizely DAM with websites. It discusses how to install the necessary package and code t...

Andrew Markham | Sep 28, 2024 | Syndicated blog

Opticon 2024 - highlights

I went to Opticon in Stockholm and here are my brief highlights based on the demos, presentations and roadmaps  Optimizely CMS SaaS will start to...

Daniel Ovaska | Sep 27, 2024

Required fields support in Optimizely Graph

It's been possible to have "required" properties (value must be entered) in the CMS for a long time. The required metadata haven't been reflected i...

Jonas Bergqvist | Sep 25, 2024

How to write a bespoke notification management system

Websites can be the perfect vehicle for notifying customers of important information quickly, whether it’s the latest offer, an operational message...

Nicole Drath | Sep 25, 2024