Thursday, August 25, 2016

Sitecore removing a rendering or sublayout programatically

Sometimes a requirement comes up to remove renderings or sublayouts from Sitecore items programatically. This could be used in the case of a pipeline to detect and remove renderings/sublayouts with broken data sources or to bulk remove/change renderings/sublayouts which have been removed/replaced.

The code below will get a Sitecore item, then all renderings on that item which fall under the default device. It then queries to find a specific rendering, and edits the item with that rendering removed.
var database = Sitecore.Data.Database.GetDatabase("master");
var item = database.Items.GetItem("/sitecore/content/Home/Test/Test-Page/");

// If item has a layout
if (item.Fields[Sitecore.FieldIDs.LayoutField] != null && !String.IsNullOrEmpty(item.Fields[Sitecore.FieldIDs.LayoutField].Value))
{
 LayoutField layoutField = new LayoutField(item.Fields[Sitecore.FieldIDs.FinalLayoutField]);
 LayoutDefinition layout = LayoutDefinition.Parse(layoutField.Value);
 DeviceDefinition device = device = layout.GetDevice("{FE5D7FDF-89C0-4D99-9AA3-B5FBD009C9F3}"); // Get the default device

 // Get renderings for the device
 var d = layout.GetDevice(device.ID.ToString());
 var ren = d.Renderings;

 // Query the renderings for a specific one - use any logic here
 var rendering = from RenderingDefinition renDef in ren
  where renDef.ItemID == "{CD8C466E-22D3-4791-9871-C230AA57F71B}"
  select renDef;

 if (rendering.FirstOrDefault() != null)
 {
  item.Editing.BeginEdit();
  d.Renderings.Remove(rendering);
  layoutField.Value = layout.ToXml();
  item.Editing.EndEdit();
 }
}
The logic could be expanded to fit the needs of your given requirements.

No comments:

Post a Comment