Add rendering to an item in Sitecore programmatically

If you need to add a rendering to an item in Sitecore programmatically, you can use the following method which takes five parameters:

1. The item on which the rendering should be added
2. The ID of the rendering
3. The position in the presentation details, where 0 is the first (top one)
4. The placeholder in which the rendering is inserted
5. If the rendering requires a datasource this goes here (absolute path or ID)

public void AddRendering(Item item, ID renderingId, int renderingPosition, string placeholder, string datasource = "")
{
    string renderingsXml = LayoutField.GetFieldValue(item.Fields[FieldIDs.LayoutField]);
    var layoutDefinition = LayoutDefinition.Parse(renderingsXml);

    if (layoutDefinition.Devices == null || layoutDefinition.Devices.Count == 0)
        throw new Exception("No available devices");

    var renderingDefinition = new RenderingDefinition
    {
        ItemID = renderingId.ToString(),
        Placeholder = placeholder,
        Datasource = datasource
    };

    foreach (DeviceDefinition device in layoutDefinition.Devices)
    {
        device.Insert(renderingPosition, renderingDefinition);
    }

    LayoutField.SetFieldValue(item.Fields[FieldIDs.LayoutField], layoutDefinition.ToXml());
}

Note that when dealing with layouts it is important to get and set the field value with LayoutField.Get/SetFieldValue(). If you fail to do this you will not process layout deltas correctly and may instead override all fields (breaking full inheritance), or attempt to get the layout definition for a delta value, which will result in you wiping the layout details when they get saved.

Add comment

Loading