Anders G. Nordby

Senior Systems Consultant at CGI

EPiServer Find: Filtering on Category


In my current project, we have a block that the editors can drag into various content areas, and which will list out courses (a content type) based on certain criteria. Now, as the CoursePage is a sort of PageData, the customer has taken advantage of the built-in EPiServer categories to tag the various courses. The CourseListBlock is of course a sort of BlockData, and we therefore agreed that tagging the CourseListBlock with categories could mean that the resulting list of courses produced should be filtered according to those categories.

Step 1: Finding the Categories from a Block

I expexted this to be straight-forward, but actually it took some time with the debugger to figure out a way to do this… For a PageData object, getting the categories is as simple as:

var categories = pageData.Category;

For a BlockData object, however, I eventually ended up with this:

// ReSharper disable once SuspiciousTypeConversion.Global
var categories = ((ICategorizable) blockData).Category;

Step 2: Building a Filter

Building a custom filter for EPiServer Find was a bit new to me, but these two links set me on the track of how to do it:

This is the extension method I ended up with (CourseWithMetaData is an object that contains the CoursePage plus some other stuff):

public static class FilterExtensions
    public static ITypeSearch<CourseWithMetaData> MatchCategories(
            this ITypeSearch<CourseWithMetaData> search, ICategorizable cats)
        var catalogBuilder = search.Client.BuildFilter<CourseWithMetaData>();

        foreach (int cat in cats.Category)
            int cat1 = cat;
            catalogBuilder = 
                catalogBuilder.Or(x => x.CoursePage.Category.Match(cat1));

        return search.Filter(catalogBuilder);

Step 3: Using the new Filter

I can now use my new filter extension method like this:

var search = _client.Search<CourseWithMetaData>();

// ReSharper disable once SuspiciousTypeConversion.Global
var cats = courseListBlock as ICategorizable;
if (cats != null && cats.Category != null && cats.Category.Any())
    search = search.MatchCategories(cats);


Works like a charm!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: