In Sitecore, one can easily get the list of all the datasources that are linked to renderings on the page.
Why do we need this?
During development, business logic may require to look for a value in all the datasources that are linked to a page.
I have seen people writing methods as below, but this can be done way more easily in one line -
private List<Item> GetRenderingDataSourceItems(Item item)
{
var items = new List<Item>();
var renderings = item.Visualization.GetRenderings(Sitecore.Context.Device, true);
foreach (var rendering in renderings)
{
//This check ensures only items are added, not queries
if (Sitecore.Data.ID.IsID(rendering.Settings.DataSource))
{
var dsItem = item.Database.SelectSingleItem(rendering.Settings.DataSource);
if (dsItem != null)
{
//Add the datasource item
items.Add(dsItem);
}
}
}
return items;
}
The following line does the same as the function above, but its much cleaner approach to do the same -
Sitecore.ExperienceEditor.Utils.ItemUtility.GetItemsFromLayoutDefinedDatasources(args.DataItem, Context.Device, args.DataItem.Language);
Hope you find it useful. Please like and subscribe for more similar blogs! Thanks :)
Comments
Post a Comment