Skip to main content

Optimizely

Optimizely Blocks As Properties: How To Hide Irrelevant Fields

Person Testing Different Business Processes

We recently ran into an issue when using shared blocks as properties on pages; some of the block’s properties don’t make any sense in this context and can lead to some confusion with editors.

Instead of creating another version of the block to use specifically as a local block, I created a simple feature to control hiding properties when a block is used as a property.

First, create an attribute to mark the properties you want hidden when the block is used as a property on another piece of content.

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class HidePropertyWhenInlinedAttribute : Attribute { }

Then, create another attribute to mark the block property itself. Here, I used IDisplayMetadataProvider to control the property display. If the above attribute is found on a property, the property will be hidden.

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class HideInlinedPropertiesAttribute : Attribute, IDisplayMetadataProvider
{
    public void CreateDisplayMetadata(DisplayMetadataProviderContext context)
    {
        var additionalData = context.DisplayMetadata.AdditionalValues;
        var extendedMetaData = additionalData[ExtendedMetadata.ExtendedMetadataDisplayKey] as ExtendedMetadata;

        var properties = extendedMetaData?.Properties ?? Enumerable.Empty<ExtendedMetadata>();

        foreach (var propertyMetaData in properties)
        {
            if (propertyMetaData.Attributes.OfType<HidePropertyWhenInlinedAttribute>().Any())
            {
                propertyMetaData.ShowForEdit = false;
            }
        }
    }
}

 

Once these are created, usage is straightforward.

Mark the properties you want to hide with the HidePropertyWhenInlined attribute.

public class ExampleBlock : BaseBlock
{
    [HidePropertyWhenInlined]
    public virtual bool IndexBlockInContentAreas { get; set; }

    public virtual bool VisibleProperty { get; set; }
}

Then, mark your block property with the HideInlinedProperties attribute

public class ExamplePage : BasePage
{
    [HideInlinedProperties]
    public virtual ExampleBlock ExampleBlock { get; set; }
}

And voilà, any marked properties will be hidden from editors in the CMS.

Example Page

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Justin Zachow

Justin Zachow is an Optimizely CMS certified full-stack developer with experience working in .NET, Typescript, Vue.js, and React. He enjoys tinkering with new technologies, hammock camping, and spending time with his pets in his free time.

More from this Author

Follow Us