Wednesday 23 April 2014

Get data source of sublayout or rendering in Sitecore

Leave a Comment
Today I noticed a post in Sitecore SDN forum regarding how to retrieve data source of sublayout or rendering for an item in Sitecore. Several sublayouts or renderings have been added in Sitecore item presentation details. We need to get data source of each sublayout.

First of all we need to get list of sublayouts or renderings used by item in Sitecore. Below function GetListOfSublayouts(string itemId) can be used to get list of sublayouts or renderings used by item in Sitecore.
 public RenderingReference[] GetListOfSublayouts(string itemId)
        {
            Sitecore.Layouts.RenderingReference[] renderings = null;
            if (Sitecore.Data.ID.IsID(itemId))
            {
                Item item = Sitecore.Context.Database.GetItem(Sitecore.Data.ID.Parse(itemId));
                if (item != null)
                {
                    renderings = item.Visualization.GetRenderings(Sitecore.Context.Device, true);
                }
            }
            return renderings;
        }
After getting list of sublayouts, iterate through each sublayout and retrieve data source value by using rendering.Settings.DataSource. Below function GetListOfDataSource(RenderingReference[] renderings) takes renderings as input parameter and return list of data source id.
RenderingReference[] renderings = GetListOfSublayouts(itemId);
List<string> ListOfDataSource = GetListOfDataSource(renderings);
public List<string> GetListOfDataSource(RenderingReference[] renderings)
        {
            List<string> ListOfDataSource = new List<string>();
            foreach (RenderingReference rendering in renderings)
            {
                ListOfDataSource.Add(rendering.Settings.DataSource);
            }
            return ListOfDataSource;
        }
Comments and suggestions are most welcome. Happy coding!

0 comments :

Post a Comment