Wednesday, 9 July 2014

How to add a sublayout to Sitecore item programmatically





 public void AddSublayoutToItem(string itemId, string sublayoutId)
        {
            using (new Sitecore.SecurityModel.SecurityDisabler())
            {
                if (Sitecore.Data.ID.IsID(itemId) && Sitecore.Data.ID.IsID(sublayoutId))
                {
                    //Get the master database and get the item on which you want to add sublayout
                    Database masterDatabase = Database.GetDatabase("master");
                    Item item = masterDatabase.GetItem(Sitecore.Data.ID.Parse(itemId));

                    //  Or you can also get Sitecore Item from Context Database as per your requirement
                    //  Item item = Sitecore.Context.Database.GetItem(Sitecore.Data.ID.Parse(itemId));

                    if (item != null)
                    {
                        // Get the layout definitions and the device definition
                        LayoutField layoutField = new LayoutField(item.Fields[Sitecore.FieldIDs.LayoutField]);
                        LayoutDefinition layoutDefinition = LayoutDefinition.Parse(layoutField.Value);
                        DeviceDefinition deviceDefinition = layoutDefinition.GetDevice(Sitecore.Context.Device.ID.ToString());

                        //Create a RenderingDefinition and add the reference of sublayout or rendering
                        RenderingDefinition renderingDefinition = new RenderingDefinition();
                        renderingDefinition.ItemID = sublayoutId;
                        //Set placeholder where the rendering should be displayed
                        renderingDefinition.Placeholder = "content";
                        // Set the datasource of sublayout, if any
                        renderingDefinition.Datasource = "{24240FF2-B4AA-4EB2-B0A4-63E027934C38}";

                        // you can also set datasource of sublayout using Sitecore Path
                        // renderingDefinition.Datasource = "/sitecore/content/Home/Books";

                        //Add the RenderingReference to the DeviceDefinition
                        deviceDefinition.AddRendering(renderingDefinition);

                        // Save the layout changes
                        item.Editing.BeginEdit();
                        layoutField.Value = layoutDefinition.ToXml(); ;
                        item.Editing.EndEdit();
                    }
                }
            }
        }







Code From : http://www.bugdebugzone.com/2014/06/how-to-add-sublayout-to-sitecore-item.html

No comments:

Post a Comment

Featured post

Getting Started With SOLR

Getting Started with Solr ·           Features o    Hit highlighting o    Auto correction o    Faceted Search o    Multi lan...