allBlogsList

Buckets and Extending Bucketing Behavior

The Problem

In a recent project, we needed to specify how a bucketable item is to be bucketed. Luckily Sitecore provides a rule-based mechanism to configure bucketable item paths. Unfortunately, the requirements would not allow us to use the action provided from Sitecore out of the box. However, since Sitecore is so extensible, we can implement a custom bucket rule action with relatively little effort.

The Solution

Sitecore provides a rule-based mechanism to configure how it builds bucketable item paths. The field used to define rule(s) is “Rules for Resolving the Bucket Folder Path:” It can be found on the “Item Buckets Settings” item under the following path in Sitecore 8.2, /sitecore/system/Settings/Buckets

Figure 1

The requirements for this feature calls for this bucketable item to be bucketed on a date field defined on the item template. However, the actions available are:

  • Based on Item Creation Date
  • Based on Item ID
  • Based on Item Name

Figure 2

No worries, since Sitecore is so extensible, we can create our own bucket rule action with very little effort. First, we need to write the class that will execute as the action.

public class DateFieldBasedPath : RuleAction where T: BucketingRuleContext
{
  public ID FieldId { get; set; }
  public string Format { get; set; }
  public override void Apply(T ruleContext)
  {
    Assert.ArgumentNotNull(ruleContext, nameof(ruleContext));
    var format = Format;
    if (string.IsNullOrEmpty(format))
    {
      format = BucketConfigurationSettings.BucketFolderPath;
    }
   
   var date = ruleContext.CreationDate;
   var item = ruleContext.BucketItem.Database.GetItem(ruleContext.NewItemId);
   if (item == null)
   {
     return;
   }
   
   DateField dateField = item.Fields[FieldId];
   if (dateField != null)
   {
     if (dateField.DateTime != DateTime.MinValue)
     {
       date = dateField.DateTime;
     }
   }
   ruleContext.ResolvedPath = date.ToString(format, Context.Culture);
   }
}

Next, we’ll need to define a new action in Sitecore. Create a new Action, Resolve Date Field Based Path, under /sitecore/system/Settings/Rules/Definitions/Elements/Bucketing.

Figure 3

Once completed, you’ll have access to it when creating a Rule for Resolving the Bucket Folder Path.

Figure 4

Now when the News Landing bucket is sync’ed, all the bucketable items under it will be organized based on the date in the Display Date field.