Thomas
Thomas

Reputation: 43

Sitecore update renderingreference

On a Sitecore 8.0 project I'm currently trying to programmatically update the datasource of a RenderingReference. Due to earlier decisions the datasource of renderings are not based in Id but on path.

With the following code im getting the rendering references, and updating the Datasources correctly within the method. But the changes are never saved to the database.

Is there something I'm doing wrong? Or am i trying to do something which is not possible?

page.Editing.BeginEdit();
var renderings = page.Visualization.GetRenderings(Sitecore.Context.Device, true);
foreach (var rendering in renderings)
{
    rendering.Settings.DataSource = "A New DataSource";
}
page.Editing.EndEdit();

Upvotes: 3

Views: 1283

Answers (1)

Marek Musielak
Marek Musielak

Reputation: 27132

You need to update the value of the __Layout field.

There is a nice blog post explaining this here: Update data source of sublayout or rendering in Sitecore.

The code goes like that:

public void UpdateRenderingDatasource(Item item, string newDatasource)
{
    //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 = newDatasource;
        // Save the layout changes
        item.Editing.BeginEdit();
        layoutField.Value = layoutDefinition.ToXml();
        item.Editing.EndEdit();
    }
}

Upvotes: 4

Related Questions