Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying sitecore rendering to new template programmatically using renderingDefinition.ItemId?

I have a custom sitecore button which changes the template of the current item, simple enough.

However as part of this I'm trying to also migrate the renderings of the old layout to a new layout if it's of a certain sublayout type by ItemId. However the ItemId that is returned is always null, the only value I get back from the RenderingDefinition is the UniqueId.

What am I doing wrong?

I have used this blog post as a guide.

The Code

public class ConvertToNewTemplateCommand : Command
{
protected void Run(ClientPipelineArgs args)
{
    if (!SheerResponse.CheckModified())
        return;

    Item item = Context.ContentDatabase.Items[args.Parameters["id"]];
    if (args.IsPostBack)
    {
        if (args.Result == "yes")
        {
            //Get current layout details
            var originalLayoutXml = item[FieldIDs.LayoutField];

            //Get new template
            TemplateItem hubTemplate = Context.ContentDatabase.GetTemplate("some guid...");
            //Change template  
            item.ChangeTemplate(hubTemplate);
            //Reset laytout
            ResetLayout(item);
            //Get reset layout
            var newLayoutXml = item[FieldIDs.LayoutField];

            //Add all the module containers to the new layout in the central column
            MoveModuleContainers(item, originalLayoutXml, newLayoutXml);
        }
    }
}

private void MoveModuleContainers(Item item, string oldXml, string newXml)
{
    var oldLayout = LayoutDefinition.Parse(oldXml);
    var newLayout = LayoutDefinition.Parse(newXml);

    bool updated = false;

    var oldRenderings = (oldLayout.Devices[0] as DeviceDefinition).Renderings;
    var newRenderings = (newLayout.Devices[0] as DeviceDefinition).Renderings;

    foreach (RenderingDefinition rendering in oldRenderings)
    {
        // Here is where the rendering.ItemID is always null
        if (rendering != null && !String.IsNullOrEmpty(rendering.ItemID) && new Guid(rendering.ItemID) == new Guid("matching guid..."))
        {
            rendering.Placeholder = "middlecolumn";
            newRenderings.Add(rendering);
            updated = true;
        }
    }

    if (updated)
    {
                   // Save item...
            }
}
}
like image 536
danmac Avatar asked Dec 03 '12 18:12

danmac


1 Answers

I got onto Sitecore support in the end which informed me that I should use:

Sitecore.Data.Fields.LayoutField.GetFieldValue(item.Fields[Sitecore.FieldIDs.LayoutField])

instead of:

item[FieldIDs.LayoutField]

to get the items layoutField correctly. This results in the rendering values being parsed correctly and as they say the rest is history.

like image 74
danmac Avatar answered Nov 15 '22 11:11

danmac