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:

/sitecore/templates/Branches/DefaultSite/$name/ContactUs.aspx

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.

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

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):

item.Editing.BeginEdit();
linkField.Url = newPath;
linkField.LinkType = "internal";
linkField.Target = "";
linkField.TargetID = newItem.ID;
item.Editing.EndEdit();

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 has 5 years of experience with developing web solutions using ASP.NET and SQL Server. For the past 3 years, he has been actively engaged in website development projects using Sitecore CMS. He enjoys creating web solutions for clients using Sitecore CMS and, using its flexibility, provides cohesive and integrated solutions. Xing is a Sitecore Technology MVP, 2016.

Explore topics:

Other Blog Posts from Xing Liu



Subscribe for insights, trends and big ideas