This is the second time I run into this – writing a feature that creates a custom content type that has a custom lookup field. The field is defined as below:
1: <Field
2: ID="createguid"
3: Type="Lookup"
4: StaticName="Reference"
5: Name="Reference"
6: DisplayName="Reference"
7: AllowMultiVote="TRUE"
8: Required="TRUE"
9: FillInChoice="FALSE"
10: Group="Custom Fields"
11: SourceID="{B45D7C95-C01B-4338-B0AF-88FFA4F3A5F1}">
12: </Field>
Notice the missing List and ShowField and WebID attributes.
When creating a redeployable solution you don’t know the GUID of a site or web that gets created during deployment – it is different every time, but the lookup field needs to know the web that contains the target list.. Simply specifying the List attribute with a URL is not enough – it did not work for me even when I had the ShowField attribute.
The only way I could get the lookup field to work is to run code that updates the field properties after the field and web objects are created. Of particular interest are the LookupList, LookupField and LookupWebId properties of the SPFieldLookup class. I placed the code in a FeatureActivated method.
Here is the feature activated code that does this:
1: private Guid _myFieldGuid = new Guid("createguid");
2:
3: public override void FeatureActivated(SPFeatureReceiverProperties properties)
4: {
5: try
6: {
7: // get web but DO NOT dispose as it belongs to SP
8: SPWeb web = properties.Feature.Parent as SPWeb;
9:
10: //get reference to the field and cast as SPFieldLookup
11: SPFieldLookup myField = web.Site.RootWeb.Fields[_myFieldGuid] as SPFieldLookup;
12:
13: //set properties
14: myField.AllowMultipleValues = true;
15: myField.PushChangesToLists = true;
16:
17: myField.LookupWebId = web.ID;
18: myField.LookupList = web.Lists["Reference"].ID.ToString();
19: myField.LookupField = "Title";
20:
21: //call Update to save changes
22: myField.Update();
23: }
24: catch (SPException ex)
25: {
26: //do something here
27: }
28: }
Hope this helps.