Posts tagged ‘adddependentlookup’

November 5, 2010

Provisioning additional view fields when provisioning lookup fields in code

When provisioning a lookup field through the UI in SharePoint 2010, there is the useful option of adding additional fields to be displayed in the view of the list. This lets us see not only the title field, as was available in 2007, but allows virtual denormalisation of data.

When provisioning lookup fields in code, however, there don’t appear, at first, to be any additional properties to allow us to set these additional view fields.

However, when we are provisioning the fields to a field collection (using the AddLookup method), there is an additional method that allows us to provision these additional view fields. The AddDependentLookup method adds this field, and can be used on any SPFieldCollection (to add the field either as a Site Column, or as a Field directly on a list).

We can, therefore, use code similar to the below to achieve this:

	using (SPWeb web = SPContext.Current.Site.OpenWeb())
            {
                SPList lookupList = web.Lists["MyList"];
                string primaryFieldName = web.Fields.AddLookup("MyCol", lookupList.ID, false);
                SPFieldLookup primaryField = web.Fields.GetFieldByInternalName(primaryFieldName) as SPFieldLookup;
                primaryField.LookupField = "Title";
                primaryField.Update();
                string dependantFieldName = web.Fields.AddDependentLookup("MyCol:SubField", primaryField.Id);
                SPFieldLookup dependentField = web.Fields.GetFieldByInternalName(dependantFieldName) as SPFieldLookup;
                dependentField.LookupField = "SubField";
                dependentField.Update();
                web.Update();
            }

We can achieve the same with CAML by setting the FieldRef attribute of the Field element on the dependent field, to the ID of the primary field, and setting the ShowField attribute to the name of the Field to show from the Lookup List. This will have to be combined with a method to set the List ID from the List Name.