Search code examples
sitecoresitecore8.1sitecore-workflow

How to remove newly created item version if there is no change with previous version in sitecore programmatically


I am creating version of item on lock & edit button. I want to remove that version if author does not change any value of that version while check in version. I would like to compare versions and delete newly created version if there is no change while check in item version.

Note: No workflow is needed


Solution

  • On ItemSaving event you can get the list of changes in the item. Here is some sample code to get the idea:

    protected void OnItemSaving(object sender, EventArgs args)
        {
            var newItem = Event.ExtractParameter(args, 0) as Item;
            Item originalItem = newItem.Database.GetItem(newItem.ID, newItem.Language, newItem.Version);
        var differences = FindDifferences(newItem, originalItem);    
    } 
    
    private List<string> FindDifferences(Item newItem, Item originalItem)
        {
            newItem.Fields.ReadAll();
            IEnumerable<string> fieldNames = newItem.Fields.Select(f => f.Name);
            return fieldNames
              .Where(fieldName => newItem[fieldName] != originalItem[fieldName])
              .ToList();
        }