This is the 6th post in a series of posts explaining the different ways of dealing with display options within Episerver. When we work with Episerver, we sometimes want to allow content editors to be able to dynamically set the width of a block on a page. In the last guide, I wrote about limiting Episerver through a validation attribute, which is my preferred method. There is a third option which is to prevent Episerver rendering the block.
The downside of this approach is that the content editor can add the block into a content area and save the page, however, they will see an error in the editor and the webpage won't contain the block. This type of approach MAY be useful if you want to create blocks that should never appear on a web page, like a settings block for example. As each website is different I thought I'd share the code in case anyone else finds it useful.
A lot of this set-up is based on the code within, How To Prevent Content Editors Adding Blocks With The Wrong Display Options.
The big difference is that instead of using the validation attribute, you would use this Initialization Module instead.
The Template Resolver Code
As you can see, when Episerver performs a template match the code is called. Like the validation tutorial, I use an interface that defines a list of invalid display options.
What Does The Error Within The Episerver Editor Look Like?
In the code, I check if the block implements this interface, if it does, I get the display option tag associated with the request, convert it to a custom enum I've created and then check the display option tag isn't on the banned list. If it is we return null. When you return null back to Episerver it will display this error message within the editor:
There you have it, as you can see you can intercept requests made by the template resolver, query the Episerver block/page that triggers the request and then modify the SelectedTemplate how you see fit. When you return null though, an error will be display in the Episerver editor. As mentioned above, the downside of this approach is that it doesn't stop the content editor saving the page, if you want this sort of functionality use a validation attribute instead.