How to create a Lookup Field From Sub-Site List to Root-Site Collection List (Cross-Site Lookup)

This solution is based on power shell script for creating cross site look up field.

For example there is a sub site http://mksportal/site1 which contains a list “Product Name”  and
there is another sub site http://mksportal/site2/site3.
In order to make cross site look up field available to sub site through content type,
this can be achieved by using power shell script.

There are couple of things mandatory, when cross site look up is created on that time both sub site and list must exist because it is dependent on list ID.
This is basic script, one can customize further like add reference field for the same lookup field mapped to other field like ID etc.
try
{

$mksWebSite =  “http://mksPortal/Site1”

$spweb = Get-SPWeb $mksWebSite
$webids=$spweb.ID

$lst = $spweb.Lists[“Product Name”]

$fieldXML = ‘
<Field ID=”GUID”
Name=”mksField”
Group=”MKS
Type=”Lookup”
DisplayName=”mksField”
StaticName=”mksField”
List=”{‘ + $lst.ID +’}”
ShowField=”Title”
Overwrite=”TRUE”
WebId=”‘ + $webids + ‘”  ></Field>’

$field = $spweb.Site.RootWeb.Fields.AddFieldAsXml($fieldXML)
$fieldRef = $spweb.Site.RootWeb.Fields.AddFieldAsXml($mksFIELDRef)
$spweb.Site.RootWeb.Update()
$ctypeParent = $spweb.Site.RootWeb.availablecontenttypes[“My Custo CType”]
$newContentType = $spweb.Site.RootWeb.ContentTypes[$ctypeParent.ID];
$fieldLink = new-object Microsoft.SharePoint.SPFieldLink($spweb.Site.RootWeb.Fields[ $fieldInternalName])
$newContentType.FieldLinks.Add($fieldLink)
$newContentType.Update()

$spweb.Dispose()

}

catch [System.SystemException]

{

write-host “Execution stopped due to: “+$_.Message -foregroundcolor Red

}

Advertisements