I need to programmatically update all of the instances of a particular rendering attached to a Sitecore item.
This is the code I first tried and failed to use:
foreach (RenderingReference renderingReference in parentRenderingReferences)
{
/* ... unrelated code removed ... */
var layoutField = new LayoutField(contentItem.Fields[FieldIDs.LayoutField]);
LayoutDefinition layoutDef = LayoutDefinition.Parse(layoutField.Value);
DeviceDefinition deviceDef = layoutDef.GetDevice(device.ID.ToString());
// Update the rendering's datasource
RenderingDefinition renderingDefinition =
deviceDef.GetRendering(renderingReference.RenderingID);
renderingDefinition.Datasource = newDataSourceValue;
/* ... unrelated code removed ... */
}
Using RenderingReference.RenderingID
in the final statement in that code didn't work, as the RenderingID
is the ID of the actual rendering item that lives in /layouts/renderings. So if the item has more than one of the same rendering on a template the code never accesses any renderings after the first instance. I tried using RenderingReference.UniqueID
, which appeared to be what I was looking for (the ID of the instance of the rendering):
foreach (RenderingReference renderingReference in parentRenderingReferences)
{
/* ... unrelated code removed ... */
var layoutField = new LayoutField(contentItem.Fields[FieldIDs.LayoutField]);
LayoutDefinition layoutDef = LayoutDefinition.Parse(layoutField.Value);
DeviceDefinition deviceDef = layoutDef.GetDevice(device.ID.ToString());
// Update the rendering's datasource
RenderingDefinition renderingDefinition =
deviceDef.GetRendering(renderingReference.UniqueID);
renderingDefinition.Datasource = newDataSourceValue;
/* ... unrelated code removed ... */
}
In this case, the resulting renderingDefinition
object is null, so that doesn't work either.