So, I came across a situation where I had to provide only selected options for a list field type(Multilist/Droplist etc) based on some conditions.
Although this was not a hard requirement and mere mapping of a parent item was acceptable, I’m more of a fan of “build code that is designed for Operations” as I have had fair share of experience in someone always misconfiguring stuffs.
Usually, I hit sitecore queries for such requirements. When we need items that are it’s ancestors or items that matches a particular template, or a child items that match a particular pattern etc
query:./ancestor::*

But it my case, the requirement was a bit difficult. I wanted to set the datasource for a droplist based on a selection made it it’s parent item’s multilist field. With Sitecore Query, I was able to traverse upto the parent item only (query:../). Via query, we cannot access an item’s field.
So explored other options,
IDataSource:
While creating a template you would have configured source item for a list type.


We can create our custom datasource by creating a class that implements Sitecore.Buckets.FieldTypes.IDataSource. This interface has one interface method Item[] ListQuery(Item item). This method returns an array of item that acts as a datasource for the list type fields.
using Sitecore.Buckets.FieldTypes;
using Sitecore.Data.Fields;
using Sitecore.Data.Items;
namespace Mark9.Foundation.SitecoreExtension.FieldDataSources
{
/// <summary>
/// Parent item's selected destination category
/// </summary>
public class ParentItemDestinationCategory : IDataSource
{
public Item[] ListQuery(Item item)
{
var destinationCategory = (MultilistField)item.Parent?.Fields["Destination Category"];
if (destinationCategory!=null) {
return destinationCategory.GetItems();
}
return new Item[0]; //Return an empty item array
}
}
}
You can map this as a data source by adding the below to the source field.
code:Mark9.Foundation.SitecoreExtension.FieldDataSources.ParentItemDestinationCategory,Mark9.Foundation.SitecoreExtension



But this would require a code deployment and if we were to make any change to the requirement it would take more time. There is another way where we can configure custom datasource for list data types using sitecore PowerShell.

We can map this script as a datasource appending it with script:
script:/sitecore/system/Modules/PowerShell/Script Library/Custom Scripts/GetSelectedCategory



One thought on “Sitecore – Ways to configure a list field’s source”