Wednesday, November 19, 2008

Lookup issue for custom content types

If you have the following situation:
You have a couple of lists in your SharePoint application and you want to export their schema.xml file (to make content types based on custom lists created by you in SharePoint). Let us suppose we have some of those lists linked with lookup columns. Then we'll have a problem:
If we'll have the Department list and the Employee list and the Employee list has a column named Department witch is a lookup to the Department list and we extract the schema.xml files from both lists (with the help of SharePoint Solution Generator or OCDExportList) and we'll make a feature with those 2 content types and after that we'll deploy the feature to a different server and we'll create instances from those content types we'll see that the relation between the instances does no longer exist. The Department lookup column from the Employee list will not refer the Department list. Why is that?
If you'll look at the schema.xml file from the Employee list you'll find that your lookup column looks like that:

<field id="{92680819-4656-406f-9eb7-21377cb4eec8}" version="1" group="" rowordinal="0" colname="int2" name="Departament" staticname="Departament" sourceid="{d129f702-1314-4fef-8bdc-4826bc720cd7}" unlimitedlengthindocumentlibrary="FALSE" showfield="Title" list="{A83FD6BE-DE5A-49A6-A369-DA72AF737408}" required="TRUE" displayname="Departament" type="Lookup">

What is interesting here is the following attribute: List="{A83FD6BE-DE5A-49A6-A369-DA72AF737408}”. This attribute tell SharePoint that the lookup field will link to the list instance with the id equals with the GUID given. When you'll deploy it to a new server, the list instance with this id does not exist anymore so it doesn't know how to link the Employee list, so the relations between your lists are not longer used.
To resolve this issue you have to make the following modification:
List="Department" - if you'll provide the name of the instance here (where SharePoint expects a GUID) when you'll create instances from your content types SharePoint will search your current web for lists with the name you provided there, if it will find something it will make the replacement for this instance.
And if you want to be more abstract you should use resources files, so we'll change the attribute with something like: List="$Resources:empmon,list_Departament;" where empmon is your resource file deployed in your 12/Resources folder, and list_Department is your mapping name for your Department list. So when you want to change the lookup for a column (to refer another list) you just have to modify your resource file and when you'll create another instance of that list the new lookup column knows to refer the right list.