Adding a web part to a List View

Adding a web part to a List View

It’s quite straightforward to add a web part to a specific library view. This can be extended to deploy a web part to every library in every web of a site collection, for example.

I developed this to deploy a web part I wrote that extracts the folder URL from the querystring in the URL, and builds a table dynamically of folder metadata, as well as a useful button for user action.

First we get the View URL, and use the LimitedWebPartManager, which works great for customizing ghosted Views. We then loop through the web parts to make sure we are not adding a web part for a second time. I found the Contains() method doesn’t work, as it compares the actual GUID, and as each web part is a new object, it will always have a new GUID.

Below is the PowerShell script to achieve it:

$FullyQualifiedWebPartName= "FolderMetaView.VisualWebPart1.VisualWebPart1" #trick: get from .DWP XML, this is the name of my web part
[Reflection.Assembly]::LoadWithPartialName("FolderMetaView.VisualWebPart1.VisualWebPart1")
$JPWeb=get-spweb "SharePoint/Div/TestWeb"
$JPLibs=$JPWeb.lists
$JPLib=$JPLibs["SimpleList"]
$Views=$JPLib.Views
$View=$Views["Specific View"]
$WebPartMgr=$JPWeb.GetLimitedWebPartManager($View.Url,[System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
$wps=$webpartmgr.get_WebParts() #get web parts
$found=$false;  #let's make sure we don't add the web part a second time
for ($wpi=0; $wpi -lt $wps.Count; $wpi++)
{
if ($WebPartMgr.WebParts[$wpi].webbrowsableobject.tostring() -eq $FullyQualifiedWebPartName)
{
$found=$true;
}
}
if (!$found) #if not found, then add it
{
$webpart=new-object  $FullyQualifiedWebPartName
$WebPartMgr.AddWebPart($webpart, "Main",0); 
}

Note Views have one web part zone called “Main”. By deploying to ZoneIndex 0, I’m putting the web part on top.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *