Monday, January 19, 2015

How to create sitecore Item from branch template using Sitecore API



Below are the code snippet to get or create Sitecore item from branch template:

public Item GetAndCreateBranchItem(string ItemName, BranchItem currentTemplate, Item parentItem)
        {
            try
            {
                if (parentItem != null)
                {
                    Item childItem = parentItem.Axes.GetDescendant(Sitecore.Data.Items.ItemUtil.ProposeValidItemName(ItemName));
                    if (childItem != null)
                    {
                        return childItem;
                    }
                    else
                    {
                        using (new SecurityDisabler())
                        {
                            childItem = parentItem.Add(Sitecore.Data.Items.ItemUtil.ProposeValidItemName(ItemName), currentTemplate);
                            return childItem;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                            }

            return null;
        }