Relocate Links from Sitecore Branch

Posted by Xing Liu on 3/6/2015

Sitecore branches are great when it comes to creating default content.  You can create a default content structure based on different user scenarios.  However, we often encounter a use case where we need links within the branch.  Out of the box from Sitecore, if you choose a link to the item within the branch, the URL will end up something like the following:


This link URL will remain once we add this branch to the content tree.  At this point, we need to create a custom event handler to handle it.  This handler will bind it to the event item:Added so that it triggers when the Item, in this case the branch, is added to the content tree.

      <event name="item:added">
        <handler type="[Namespace].Classname, [Assembly]" method="OnItemAdded" patch:after="processor[@type='Sitecore.Data.Fields.ItemEventHandler, Sitecore.Kernel']">

In the handler code, you need to define the default branch location.  In this case, it will be:

private const string BranchFolderPath = "/sitecore/templates/Branches";
protected void OnItemAdded(object sender, EventArgs args)
            // The first [0] item contains the target item 
            Item target = Event.ExtractParameter(args, 0) as Item;
            if (target != null)
                if (target.Branch != null)
                    this.RelocateLink(Sitecore.Context.ContentDatabase, target, target, target.Branch.InnerItem);

After you have the default path(BranchFolderPath), you need to replace the $name keyword with the correct path of the link item.  Here is the code that does the replacement.

var oldPath = linkField.TargetItem.Paths.FullPath;
var newPath = oldPath.Replace(string.Format("{0}/$name", rootBranchItem.Paths.FullPath), rootItem.Paths.FullPath);
var newTargetItem = db.GetItem(newPath);

After you get the newTargetItem, edit the linkField variable to updated the new target (Make sure to wrap the editing code wit item.Editing.BeginEdit/item.Editing.EndEdit):

linkField.Url = newPath;
linkField.LinkType = "internal";
linkField.Target = "";
linkField.TargetID = newItem.ID;

That’s it.  Now you can enjoy the benefit of a branch as well as creating the default link within the Sitecore branch.


Looking for a partner who will exceed your expectations? Get in touch.

SYMSOFT SOLUTIONS 4090 Truxel Road, Suite 200 Sacramento, CA 95834
United States (916) 567-1740