Automatically provisioning SharePoint related lists

SharePoint 2010 allows you to create a list relationship and identify relationship behavior when items from related list get deleted.
Your options are to either: restrict the delete of items on which other items depend on or cascade delete all of the dependants.
When such related lists have to be implemented on multiple sites of your SharePoint 2010 solution – you can use PowerShell to automate the provisioning.
I assume you’re running a 2010 IW Demo VM available from Microsoft.
This is the VM we’ll be using here to demonstrate the scripting approach.
1. From the Virtual Machine, open SharePoint 2010 Management Shell.
2. Execute the following script:

$ParentList = "Parent List"
$ChildList = "Child List"

$SPSite = Get-SPSite | Where-Object {$_.Url -eq "http://intranet.contoso.com"}
  if($SPSite -ne $null)
  {
$RootWeb = $SPSite.RootWeb
$CustomListTemplate = $RootWeb.ListTemplates["Custom List"]
$NewChildListInstance =
$RootWeb.Lists.Add($ChildList, $ChildList, $CustomListTemplate)
$SPChildList = $RootWeb.Lists[$NewChildListInstance]
$SPChildList.OnQuickLaunch = $true
$SPChildList.Update()

$NewParentListInstance =
$RootWeb.Lists.Add($ParentList, $ParentList, $CustomListTemplate)
$SPParentList = $RootWeb.Lists[$NewParentListInstance]
$SPParentList.OnQuickLaunch = $true
$SPParentList.Update()

$ListFields = $SPChildList.Fields
$LookupField =
$ListFields.AddLookup("Parent Reference", $NewParentListInstance, $false)
$LookupFieldInstance = $ListFields.GetField($LookupField)
$LookupFieldInstance.RelationshipDeleteBehavior =
[Microsoft.SharePoint.SPRelationshipDeleteBehavior]::Cascade
$LookupFieldInstance.Indexed = $true
$LookupFieldInstance.PushChangesToLists = $true
$LookupFieldInstance.Update()
$SPChildList.Update()

$ListView = $SPChildList.DefaultView
$ListViewFields = $ListView.ViewFields
$ListViewFields.Add($LookupFieldInstance)
$ListView.Update()
  }

Above, we create two lists, Parent and Child list. Child list has a lookup field defined in it. When a new item is created in the child list, a user can associate a lookup field value to the item in the Parent list.
Later when the parent item is deleted, all of the child items will be deleted along with it. Alternatively, you can specify [Microsoft.SharePoint.SPRelationshipDeleteBehavior]::Restrict
This will ensure the user will not be able to delete a related item and will be informed about list item relationship.
For more SharePoint 2010 handy solutions and tips like this one – check out my new book.

Enjoy!

This entry was posted in sharepoint 2010 and tagged , , . Bookmark the permalink.

Comments are closed.