I came across business requirement in Sitecore where for few items we don't need to attached workflow but we want to create new version when we lock edit the item.
I cant apply below setting as it will impact all the items and my workflow will not useful.
<setting name="RequireLockBeforeEditing" value="true"/>
I also gone through stackoverflow question and it has given below solution but not sure on which event it should be.
public Item StartEditing(Item item)
{
Error.AssertObject((object) item, "item");
if (!Settings.RequireLockBeforeEditing || Context.User.IsAdministrator)
return item;
if (this._context.IsAdministrator || StandardValuesManager.IsStandardValuesHolder(item) || !this.HasWorkflow(item) && !this.HasDefaultWorkflow(item) || !this.IsApproved(item))
return this.Lock(item);
Item obj = item.Versions.AddVersion();
if (obj != null)
return this.Lock(obj);
else
return (Item) null;
}
Try something like this:
Patch item:saved event:
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<events>
<event name="item:saved">
<handler type="PersonalizationDemo.Data.Items.ItemEventHandler, PersonalizationDemo" method="OnItemSaved"/>
</event>
</events>
</sitecore>
</configuration>
Implement class of custom event handler:
namespace PersonalizationDemo.Data.Items
{
using Sitecore.Data.Items;
using Sitecore.Events;
using System;
public class ItemEventHandler
{
protected void OnItemSaved(object sender, EventArgs args)
{
if (args == null) { return; }
var sitecoreEventArgs = args as SitecoreEventArgs;
if (sitecoreEventArgs == null) { return; }
if (sitecoreEventArgs.Parameters.Length < 2) { return; }
var item = sitecoreEventArgs.Parameters[0] as Item;
if (item == null) { return; }
if (!this.ShouldItemBeProcessed(item)) { return; }
var itemChanges = sitecoreEventArgs.Parameters[1] as ItemChanges;
if (itemChanges == null) { return; }
if (itemChanges.FieldChanges.Contains(Sitecore.FieldIDs.Lock))
{
var fieldChange = itemChanges.FieldChanges[Sitecore.FieldIDs.Lock];
if (fieldChange.Value == "<r />") { return; }
this.CreateNewVersion(item);
}
}
protected bool ShouldItemBeProcessed(Item item)
{
// TODO implement necessary check
return true;
}
protected void CreateNewVersion(Item item)
{
var newItem = item.Versions.AddVersion();
newItem.Editing.BeginEdit();
// update necessary field if you need that
newItem.Editing.EndEdit();
}
}
}