Reputation: 525
For one of a project requirement I suppose to add a sublayout to item at runtime, and this sublayout should be added to devices ( Default , Printer ), So I used the following code:
Item item = GetDatabase().GetItem(Sitecore.Data.ID.Parse(itemId));
if (item != null)
{
LayoutField layoutField = new LayoutField(item.Fields[Sitecore.FieldIDs.LayoutField]);
LayoutDefinition layoutDefinition = LayoutDefinition.Parse(layoutField.Value);
string[] targetedDevices = new string[] { "{FE5D7FDF-89C0-4D99-9AA3-B5FBD009C9F3}", "{46D2F427-4CE5-4E1F-BA10-EF3636F43534}" };
foreach (var device in targetedDevices)
{
DeviceDefinition deviceDefinition = layoutDefinition.GetDevice(device);
RenderingDefinition renderingDefinition = new RenderingDefinition();
renderingDefinition.ItemID = sublayoutId;
renderingDefinition.Placeholder = "column-content";
deviceDefinition.AddRendering(renderingDefinition);
}
// Save the layout changes
item.Editing.BeginEdit();
layoutField.Value = layoutDefinition.ToXml(); ;
item.Editing.EndEdit();
}
My Question is, Is there another way of selecting the presentation devices like sitecore API? As I am hardly coded the IDs of the targeted devices.
Upvotes: 2
Views: 771
Reputation: 2096
I have not seen any specific API a far as I have navigated though Sitecore.Kernel.dll unfortunately. Maybe there is some third party sitecore extension that warp and extend this functionality, but again, I am now aware about that.
Important point to note: I noticed from the code mentioned above: You are accessing
item.Fields[Sitecore.FieldIDs.LayoutField]
and that is valid for Sitecore version up to 7. But as Sitecore 8 introduced Versioned Layouts you should use
item.Fields[Sitecore.FieldIDs.FinalLayoutField]
instead. Hope that helps.
Upvotes: 4