On most Episerver projects, there will be a requirement for content editors to select more options out of a dropdown list or a checkbox property. In Episerver this is done via a selection factory. Like the EPIC developers that we are, when we're building our websites we want to stick to the DRY principle (don't repeat yourself) and we don't want to have to create a new selection factory property every time that we want to display different data within the CMS. The best way to do this is to create a generic selection factory that can be reused. If you want to learn how to do this, read on!
How Do I Pass A Parameter Into A Selection Factory?
First, let's look at the code to associate a selection factor onto an exisiting property:
Notice on Line4 that a type
is passed into the selection factory. This is how we can make a generic selection factory. Next, we look at the selection factory code:
GetSelections()
is the method Episerver calls when it tries to get the data. The input parameter is an ExtendedMetadata
. If you look in here you can see that it contains a property called Attributes
. This technique is how we can pass information from our class/block definitions into a selection factory. We create a custom attribute, declare it on the same property we want to set as a selection factory. When the selection factory gets called, we then read the contents of that attribute. So let's dig into some code:
Our property declaration now looks like this:
Our selection factory code will now look something like this:
Passing parameters is possible when you use a selection factory, however, the way you need to do it isn't that obvious. When you want to pass in a parameter, you need to pass value via custom attributes, rather than directly through the selection factories constructor. Happy Coding 🤘