Monday, March 24, 2014

Caveats when using Summary Link Web Part in a Web Template

My scenario was that the Summary Link Web Part had been used on a site which was to be saved as a site template using the UI (Save site as template). Saving the template worked fine, but once you created a new site based on the template you got the infamous “List does not exist” error.

The reason for the error is that the SummaryLinkWebPart class inherits the DataFormWebPart class, which has a property called ListId. If the page which hosts the Summary Links Web Part is located in for example SitePages, then the id will point to that list. Once you save the template, this id will come along, and will of course not exist in the new site.

When it comes to the Summary Link Web Part it really don’t need a reference to a list, as it’s storing all the data inside the web part itself. To fix up the template site before saving it I wrote the following PowerShell script.

function FixWebpart($wpm) {
$count = $wpm.WebParts.Count-1
ForEach ($number in 1..$count )
{
$webpart = $wpm.WebParts[$number]
# Check if it's a summary link web part
if( $webpart.PsObject.TypeNames[0] -eq 'Microsoft.SharePoint.Publishing.WebControls.SummaryLinkWebPart' ) {
write-host "Fixing listid - " + $webpart.Title + " : " + $webpart.ID
# Set the id to a blank GUID
$webpart.ListId = [guid]::Parse("00000000-0000-0000-0000-000000000000")
$wpm.SaveChanges($webpart)
}
}
}

#Get a reference to the template site
$web = get-spweb https://intranet.contoso.com/sites/template
$list = $web.Lists.TryGetList("Site Pages")

foreach($item in $list.Items) {
$wpm = $web.GetLimitedWebPartManager($item.Url, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
FixWebpart($wpm)
}