DropDownList Category Picker in Episerver 7
A client needed the editors to be able to select one category from a SELECT box. I knew there were some built-in controls to make things like this easy in Epi CMS 7.
Looking around these two posts helped me to find what I think is the best way:
- Episerver 7: Configuring editors for your properties by Linus Ekström
- A filtered page reference property by Joel Abrahamsson
In my case I needed the children and grandchildren of a configured root category as possible items.
namespace Krompaco.Project.Site
{
using System.Collections.Generic;
using EPiServer.DataAbstraction;
using EPiServer.Shell.ObjectEditing;
public class CategorySelectionFactory : ISelectionFactory
{
public IEnumerable<ISelectItem> GetSelections(ExtendedMetadata metadata)
{
var list = new List<SelectItem>();
var root = Category.Find(yourIdInteger);
foreach (Category country in root.Categories)
{
list.Add(new SelectItem
{
Text = country.LocalizedDescription.ToUpper(),
Value = country.ID.ToString()
});
foreach (Category region in country.Categories)
{
list.Add(new SelectItem
{
Text = region.LocalizedDescription,
Value = region.ID.ToString()
});
}
}
return list;
}
}
}
Then you need to do this to make the UIHint mean something. Seems like there are problems having an int TargetType but I can live with having the property stored as a string.
namespace Krompaco.Project.Site
{
using System;
using System.Collections.Generic;
using EPiServer.Shell.ObjectEditing;
using EPiServer.Shell.ObjectEditing.EditorDescriptors;
[EditorDescriptorRegistration(
TargetType = typeof(string),
UIHint = "project-category-select")]
public class CategorySelector : EditorDescriptor
{
public override void ModifyMetadata(ExtendedMetadata metadata, IEnumerable<Attribute> attributes)
{
SelectionFactoryType = typeof(CategorySelectionFactory);
// If on 7.0 and not 7.1 this has a slightly different syntax (more dots)
ClientEditingClass = "epi-cms/contentediting/editors/SelectionEditor";
base.ModifyMetadata(metadata, attributes);
}
}
}
Then just decorate properties with the same UIHint like this:
[UIHint("project-category-select")]
[Display(
Name = "Primary category",
GroupName = SystemTabNames.Content,
Order = 900)]
public virtual string PrimaryCategoryId { get; set; }
In Edit Mode you'll then get a sleek DropDownList like this.
Published and tagged with these categories: Episerver, Development