Relocate Links from Sitecore Branch

Xing Liu • 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.

Xing Liu

Xing Liu is a Sitecore MVP with expertise in all aspects of ASP.NET and SQL Server development across a variety of industries including Government, Banking, Healthcare and Energy. He provides technical thought leadership and consulting to SymSoft and client development teams. Xing has deep expertise in using Sitecore Helix in an Agile delivery model to streamline the construction of complex Sitecore websites, portals and their associated authoring environments. Xing is also a globally recognized photographer with an Instagram following approaching 100,000.

Explore topics:

Other Blog Posts from Xing Liu