Monday, April 3, 2017

Sitecore custom personalization rule with value selection for content editors

Custom personalization rules in Sitecore are a great way of using custom business logic/conditions to build personalized experiences for a web site's users. These rules will often require the content editor to enter a value when creating the rule in the rule builder interface. An example of this might be a rule used to personalize on a user's car make. The rule could be "Where the user's car make is Car Make".

Instead of requiring a content editor to type that car make in (which creates opportunity of user error and creates a rule that can never be true), the rule can instead be configured to allow the content editor to select from a list of predefined values.

How this works is that, in the content tree a parent node will be setup to contain all items which the content editor will select from. Any template can be used, and ultimately it's the item's ID which will be passed to the rule processor.


The rule text will then be defined as:
Where the user's car make is [carMakeID,Tree,root={63A00CEE-0711-42CF-9B40-6B8C81EF6537},Car Make]
 The squared bracketed token contains 4 parameters:
  1. The name of the property in the .NET class for the rule
  2. Tree - indicates this is a tree selection
  3. Root which points to the parent item's ID in the tree. In this case it's the Car Makes folder above.
  4. Text that is displayed in the rule set editor
Now the actual rule processor code:
namespace MyProject
{
    public class CarMakeRule<T> : WhenCondition<T> where T : RuleContext
    {
        // Fields
        private string carMakeID;

        // Methods
        public CarMakeRule()
        {
            carMakeID = string.Empty;
        }

        // Properties
        public string CarMakeID
        {
            get { return (carMakeID ?? string.Empty); }
            set
            {
                Assert.ArgumentNotNull(value, "carMakeID");
                carMakeID = value;
            }
        }

        protected override bool Execute(T ruleContext)
        {
            try
            {
                Assert.ArgumentNotNull(ruleContext, "ruleContext");

                // Logic goes here
    // carMakeID is the item ID for the selection
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}
When the content editor uses the rule, Instead of typing the value in, a box will popup to make the selection.