Tuesday, May 27, 2008

Programmatically Creating Lookup Fields

In my wanderings across the net I've found many different ways to accomplish this but for whatever reason they weren't working consistently for me. After further delving I came across the following snippet of code from the Tech MOSS Team. Again, for whatever reason I couldn't get it to work consistently. Upon further looking at the SPWeb.Fields.AddLookup method, I saw that this returned a string representing the internal field name. This is where the light went on for me. Using this returned value in combination with SPWeb.Fields.GetFieldByInternalName always resulted in success for me.
Hope this helps for anyone else trying this out. The method below is part of a Feature Receiver class used in a Feature.

public static SPFieldLookup CreateLookupField(string fieldName, string group, string fieldDescription, bool required, bool allowMultipleValues, SPWeb w, SPList lookupList, string lookupField)
{


string internalFieldName = "";

// add a Lookup field with the passed in information
// Note: This method returns a string with the interna field name. This is REQUIRED for the next line to successfully
// retrieve the lookup field
internalFieldName = w.Fields.AddLookup(fieldName, lookupList.ID, lookupList.ParentWeb.ID, required);
// cast created field to a SPLookup
SPFieldLookup lookup = (SPFieldLookup)w.Fields.GetFieldByInternalName(internalFieldName);
// value additional attributes based on passed parameters
lookup.AllowMultipleValues = allowMultipleValues;
lookup.Description = fieldDescription;
lookup.Group = group;
lookup.LookupField = lookupField;
// update the lookup field...this is required whenever modifying properties of the SPLookup lookup.Update(true);
// return/pass back the lookup field
return lookup;

}

No comments: