1

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?

4

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);
            }
        }
    }
}
  • 3
    Make sure to include checks for Context Database, parent Template ID and so on. Don't want this handler bleeding out all over the place. Remember; OnItemCreated is called for each and every new item published for instance; presumably you only want this working on the CM server. – Mark Cassidy Mar 14 '17 at 11:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.