Programmatically add new version of a Sitecore item

Programmatically add a new version of an item in Sitecore

This is a pretty easy concept but lately I've been hearing that most of the blog posts generated don't really help beginners new to Sitecore. I decided that I would occasionally slip in a basic concept for the beginners. First in the series: Programmatically adding a new version of a Sitecore item.

Use case: My intranet website now allows employees (with proper permissions) to edit project details within the intranet site. The thing that scared me about this approach was that I could easily envision an employee overwriting the field value and having their boss say - "why did you update that, please go back to previous copy"

So when an employee edits the item from the website, I create a new version of the item. This allows me to roll back to the older version when needed. The code is really simple too.


//disable security - optional step
using (new Sitecore.SecurityModel.SecurityDisabler())
{
 //create new version of item that you are editing
 Item LatestItemVersion = ItemToVersion.Versions.AddVersion();
 //Begin Editing
 LatestItemVersion.Editing.BeginEdit();
 //do something to item
 //End Editing
 LatestItemVersion.Editing.EndEdit();
}

Comments