views:

1773

answers:

2

I need a choice field (in a site column) to reference a list I am importing into sharepoint. This list will very infrequently be updated to add additional choices. How would I create this column? Programmatically?

Well see it is a lookup per say... just trying to figure out how to code it... I'm assuming I need to import the list first as a new content type. Then create a lookup column (with multiple) for the content type?!?

A: 

It sounds like a Lookup column is what you're looking for. You'd have to import the list first, and then create the lookup as a site column.

DylanW
Well see it is a lookup per say... just trying to figure out how to code it...I'm assuming I need to import the list first as a new content type. Then create a lookup column (with multiple) for the content type?!?
+6  A: 

Here's some code that will add a lookup field to an exsisting content type.

If your using list definitions then this is the only way a lookup field can be included. It can't be added into the CAML of the list definition because a guid for the lookup list is required and this is not known before hand. SharePoint autogenerates this Guid when the list is created.

So you need to first create the lookup column inside the root SPWeb of the SPSite

private void CreateLookup(SPWeb web, SPList lookupList, String lookupField, String fieldName, String fieldGroup, bool allowMultiLookup)
{
    using (SPSite site = web.Site)
    {
        using (SPWeb rootWeb = site.RootWeb)
        {
            rootWeb.Fields.AddLookup(fieldName, lookupList.ID, web.ID, false);
            SPFieldLookup fieldLookup = (SPFieldLookup)rootWeb.Fields[fieldName];
            if (fieldLookup == null) return;
            fieldLookup.AllowMultipleValues = allowMultiLookup;
            fieldLookup.LookupField = lookupField;
            fieldLookup.Group = fieldGroup;
            fieldLookup.Title = fieldName;
            fieldLookup.Update(true);
        }
    }
}

And then you'll need to add this field to the exsisting content type

private void AddLookupToContentType(SPWeb web, String fieldName, String contentTypeName)
{
    using (SPSite site = web.Site)
    {
        using (SPWeb rootWeb = site.RootWeb)
        {
            SPFieldLookup lookupField = (SPFieldLookup)rootWeb.Fields[fieldName];
            if (lookupField == null) return;
            SPContentType riskContentType = rootWeb.ContentTypes[contentTypeName];
            if (riskContentType == null) return;
            riskContentType.FieldLinks.Add(new SPFieldLink(lookupField));
            riskContentType.Update(true);
        }
    }
}
Dan Revell