1- Creating the class that will delete the field:
The class will be used as an handler in the On Item Copied event. Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sitecore.Data.Items;
using Sitecore.Events;
using MyProject.Common.Constants;
using Sitecore.Configuration;
namespace MyProject.Business.Sitecore.Events.ItemCopied
{
public class ClearFields
{
///
/// Clear fields to avoid duplicate data when copying or duplicating item on Authoring
///
///
///
protected void OnItemCopied(object sender, EventArgs args)
{
if (args != null)
{
Item item = Event.ExtractParameter(args, 1) as Item;
if (item == null)
return;
foreach (var field in GetFieldsToClear())
{
if (!string.IsNullOrEmpty(item[field]))
{
item.Editing.BeginEdit();
item.Fields[field].Value = "";
item.Editing.EndEdit();
}
}
}
}
private static List GetFieldsToClear()
{
string strFields = Settings.GetSetting(SitecoreSettings.ClearFieldsName);
return strFields.Split('|').Select(strField => strField.Trim()).ToList();
}
}
}
You will notice we have stored the field names in a sitecore settings so we could add more if need to extend it later on.
2- Hook the event in the configuration file:
< event name="item:copied">
< handler type="MyProject.Business.Sitecore.Events.ItemCopied.ClearFields, MyProject.Business" method="OnItemCopied" />
< /event>
Here we go, now when copying an item you will be able to clear the Rich Text Editor field, the Meta Data...
No comments:
Post a Comment