sitecoresitecore7sitecore7.2bucketsitecore8

Sitecore 8: Sync a bucket item on save


I have seen how we can provide default conditions and default actions to newly created bucket items. I also know that we can create a custom rule for building path based on custom date field.

But, how can we set the item path when the date field is and the is saved. Consider an example. We have a bucket item template say "News" which has a date field say "Release Date". We have the settings where on item creation, the item path has the creation date like "/News/2015/09/16/item1". Now, we need to have some logic where we can change the path when the "release date" of "item1" is updated and the item is Saved.

How can we update the item path when item's release date is updated and item is Saved !! do i need to implement some logic in OnItemSaved() method ?

I already went through posts on GeekHive


Solution

  • The simplest way to do this would be to hook into the item:saved event and sync the bucket in there. The following code is untested:

    public class ItemSavedEventHandler
    {
        public void Execute(object sender, ItemSavedEventArgs args)
        {
            Assert.IsNotNull(sender, "sender is null");
            Assert.IsNotNull(args, "args is null");
    
            // WARNING: using the events disabler is not recommended in this case. 
            // If you do this, the path of the item in question will not be updated and will cause issues when you edit the page and try to specify rendering data sources (the locations won't resolve)
            using (new EventsDisabler())
            {
                var parameter = args.Item;
                if (!BucketManager.IsItemContainedWithinBucket(paremeter))
                {
                    return;
                }
    
                var bucketItem = parameter.GetParentBucketItemOrParent();
                if (!bucketItem.IsABucket())
                {
                    return;
                }
    
                BucketManager.Sync(bucketItem);
            }
        }
    }
    

    On a bucket with a lot of items, this will considerably slow down the save process tho.