tedgustaf.se

Denote required properties in Episerver

This code snippet shows how to add an asterisk to the property names of all required properties in Episerver.

  • Ted Nyberg
  • 1 September 2016
  • 0

To make it easier for editors to see which Episerver properties are required, you can automatically customize the property meta data to modify the property display names.

For this example, this means all required properties appear with an asterisk after the display name in edit mode:

We accomplish this by customizing the meta data through a type implementing IMetadataExtender:

C# Expand
public class RequiredPropertiesMetadataExtender : IMetadataExtender
{
    public void ModifyMetadata(ExtendedMetadata metadata, IEnumerable<Attribute> attributes)
    {
        // Add asterisk to required (editable) properties
        metadata.Properties.OfType<ContentDataMetadata>()
                           .Where(p => p.IsRequired && !p.IsReadOnly)
                           .ForEach((property) => { property.DisplayName = $"{property.DisplayName} (*)"; });
    }
}

Finally, we register our meta data extender with the following initialization module:

C# Expand
[InitializableModule]
[ModuleDependency(typeof (InitializableModule))]
public class RequiredPropertiesMetadataExtenderInitialization : IInitializableModule
{
    public void Initialize(InitializationEngine context)
    {
        if (context.HostType == HostType.WebApplication)
        {
            var registry = context.Locate.Advanced.GetInstance<MetadataHandlerRegistry>();

            registry.RegisterMetadataHandler(typeof(ContentData), new RequiredPropertiesMetadataExtender());
        }
    } 
        
    public void Preload(string[] parameters) { } 
        
    public void Uninitialize(InitializationEngine context) { }
}

Note: As Mattias pointed out in the comments, this example doesn't work for localized property names.