Wednesday, 11 June 2014

Update data source of sublayout or rendering in Sitecore

Leave a Comment
In this article I am going to explain how to change data source of sublayout or rendering in Sitecore programmatically. Also you can check article on how to get data source of sublayout or rendering in Sitecore programmatically.

Several sublayouts or renderings have been added in Sitecore item presentation details. We need to change data source of each sublayout and set data source value to any other value. Below function UpdateRenderingDatasource(string itemId) takes Sitecore item id as input and change data source of sublayouts or renderings.
      public void UpdateRenderingDatasource(string itemId)
            using (new Sitecore.SecurityModel.SecurityDisabler())
                if (Sitecore.Data.ID.IsID(itemId))
                    Item item = Sitecore.Context.Database.GetItem(Sitecore.Data.ID.Parse(itemId));
                    if (item != null)
                        //Get all added renderings
                        Sitecore.Layouts.RenderingReference[] renderings = item.Visualization.GetRenderings(Sitecore.Context.Device, true);
                        // Get the layout definitions and the device
                        LayoutField layoutField = new LayoutField(item.Fields[Sitecore.FieldIDs.LayoutField]);
                        LayoutDefinition layoutDefinition = LayoutDefinition.Parse(layoutField.Value);
                        DeviceDefinition deviceDefinition = layoutDefinition.GetDevice(Sitecore.Context.Device.ID.ToString());
                        foreach (RenderingReference rendering in renderings)
                            // Update the renderings datasource value accordingly 
                            deviceDefinition.GetRendering(rendering.RenderingID.ToString()).Datasource = "{EDDF6E49-28C4-4699-9E12-4E69B5A64D1A}";
                            // Save the layout changes
                            layoutField.Value = layoutDefinition.ToXml();
Explanation: First of all we need to get list of sublayouts or renderings used by item in Sitecore. Below code gets all added renderings or sublayouts.
Sitecore.Layouts.RenderingReference[] renderings = item.Visualization.GetRenderings(Sitecore.Context.Device, true);
If you want to get particular sublayout or rendering then use below code by using specific sublayout id.
  Sitecore.Layouts.RenderingReference[] renderings = item.Visualization.GetRenderings(Sitecore.Context.Device, true).Where(r => r.RenderingID == Sitecore.Data.ID.Parse(sublayoutId)).ToArray();
Once you get list of renderings then get the layout definition and device definition. Iterate through every rendering and update the rendering data source accordingly and save the layout changes.

Comments and suggestions are most welcome. Happy coding!


Post a Comment