World is now on Opti ID! Learn more

Paul Gruffydd
Oct 30, 2018
  52
(0 votes)

Limiting total items in a content area while supporting personalisation

As anyone who’s spoken to me at any length about Episerver can confirm, I’m something of a fan of Episerver’s inbuilt visitor group personalisation capabilities. It’s easy to use and, done right, can add a load of value for next to no effort but all too often I see it forgotten about during builds. The most common occurrence of this that I see is the use of a ContentArea’s Items collection rather than FilteredItems but I was reminded of another by Aniket’s recent(ish) blog post.

It’s a technique I’ve seen both in various blog posts and out in the wild being used on sites but, while it does exactly as it claims (sets a maximum number of items you’re allowed to add to a content area), it’s probably not what you need. Why? Take a look…

In this example we’ve got a content area for a hero carousel which can display no more than 3 blocks. To enforce this, I’ve added the validation attribute described in the posts linked above to limit the maximum number of items in the content area to 3. I’ve then set up some blocks so that only 3 will display. All good?

Well, not really. Even though only 3 items will display, the validation attribute will throw a validation error because it doesn’t consider personalisation. If we remove items until it stops throwing an error, in this instance we’d end up with only a single item being displayed on the site.

To fix the issue we could use FilteredItems as I mentioned above and that would kind of work but then consider this scenario…

As the editor will always be logged in and the validation will run in the context of the editor, the first item would be filtered out and so, even though we could quite feasibly return 4 items from the FilteredItems collection for a user viewing the site, the validation will let that through.

A better alternative would be to look at each of the content area items in the Items collection and check whether they’re part of a personalisation group. We can then total up the number of groups plus the number of items which aren’t in a group and that will give us the maximum number of items in the content area after they have been filtered.

Putting it all together, we get this:

/// <summary>
/// Sets the maximum item count in a content area once personalisation is applied
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class MaxItemsAttribute : ValidationAttribute
{
    private int _maxAllowed;

    public MaxItemsAttribute(int MaxItemsAllowed)
    {
        _maxAllowed = MaxItemsAllowed;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var contentArea = value as ContentArea;

        // Get all items or none if null
        var allItems = contentArea?.Items ?? Enumerable.Empty<ContentAreaItem>();

        // Count the unique personalisation group names, replacing empty ones (items which aren't personalised) with a unique name
        var i = 0;
        var maxNumberOfItemsShown = allItems.Select(x => string.IsNullOrEmpty(x.ContentGroup) ? (i++).ToString() : x.ContentGroup).Distinct().Count();

        return (maxNumberOfItemsShown > _maxAllowed) ? new ValidationResult($"The property \"{validationContext.DisplayName}\" is limited to {_maxAllowed} items") : null;
    }

}

Which we can use like this:

[Display(Name = "Hero Carousel")]
[AllowedTypes(typeof(HeroItem))]
[MaxItems(3)]
public virtual ContentArea HeroCarousel { get; set; }
Oct 30, 2018

Comments

Please login to comment.
Latest blogs
Make Global Assets Site- and Language-Aware at Indexing Time

I had a support case the other day with a question around search on global assets on a multisite. This is the result of that investigation. This co...

dada | Jun 26, 2025

The remote server returned an error: (400) Bad Request – when configuring Azure Storage for an older Optimizely CMS site

How to fix a strange issue that occurred when I moved editor-uploaded files for some old Optimizely CMS 11 solutions to Azure Storage.

Tomas Hensrud Gulla | Jun 26, 2025 |

Enable Opal AI for your Optimizely products

Learn how to enable Opal AI, and meet your infinite workforce.

Tomas Hensrud Gulla | Jun 25, 2025 |

Deploying to Optimizely Frontend Hosting: A Practical Guide

Optimizely Frontend Hosting is a cloud-based solution for deploying headless frontend applications - currently supporting only Next.js projects. It...

Szymon Uryga | Jun 25, 2025

World on Opti ID

We're excited to announce that world.optimizely.com is now integrated with Opti ID! What does this mean for you? New Users:  You can now log in wit...

Patrick Lam | Jun 22, 2025

Avoid Scandinavian Letters in File Names in Optimizely CMS

Discover how Scandinavian letters in file names can break media in Optimizely CMS—and learn a simple code fix to automatically sanitize uploads for...

Henning Sjørbotten | Jun 19, 2025 |