Denote required properties in Episerver

Denote required properties in Episerver

1 minutes

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

Migrated article

This article was migrated from an older iteration of our website, and it could deviate in design and functionality.

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:

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:

[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.

Last updated: 2017-04-18