I know that I can reference a parent item with Glass Mapper, but I need to copy a specific field on my child because I need to facet on it.
What is the best way to copy a field from my parent item on creation?
Sitecore Stack Exchange is a question and answer site for developers and end users of the Sitecore CMS and multichannel marketing software. It only takes a minute to sign up.
Sign up to join this communityI know that I can reference a parent item with Glass Mapper, but I need to copy a specific field on my child because I need to facet on it.
What is the best way to copy a field from my parent item on creation?
You can add your own handler to item:created
event and get the field value from parent.
First register your handler:
<event name="created">
<handler type="YourNameSpace.YourHandler, YourAssembly" method="OnItemCreated" />
</event>
And the code:
namespace YourNamespace
{
public class YourHandler
{
private static ID _childTemplateId = ID.Parse("YOUR_TEMPLATE_ID");
private static ID _parentTemplateId = ID.Parse("YOUR_PARENT_TEMPLATE_ID");
private const string FieldName = "YOUR_FIELD_NAME";
public void OnItemCreated(object sender, EventArgs args)
{
try
{
using (new SecurityDisabler())
{
ItemCreatedEventArgs arg = Event.ExtractParameter(args, 0) as ItemCreatedEventArgs;
if (arg == null || arg.Item == null || arg.Item.Parent == null)
return;
var item = arg.Item;
var parent = arg.Item.Parent;
if (item.TemplateID != _childTemplateId)
return;
if (parent.TemplateID != _parentTemplateId)
return;
if (item.Database.Name != "master")
return;
item.Editing.BeginEdit();
item[FieldName] = parent[FieldName];
item.Editing.EndEdit();
}
}
catch (Exception exc)
{
Log.Error("Exception while copying field value from parent", exc);
}
}
}
}