Thursday, April 26, 2012

Error while adding Site columns (fields) to list content types

Recently, I had a situation where I need to add site columns (available in root web) to a content type reference in a particular list under a particular web.

I wrote the code below 
 
var field = web.Site.RootWeb.AvailableFields[new Guid("<<FieldID>>")];
foreach (SPContentType cType in web.Lists["ListName"].ContentTypes)
{
    cType.Fields.Add(field);
    cType.Update();
}

but it was not working as expected and throwing the below exception

"This functionality is unavailable for field collections not associated with a list."

After some research, I came to know that the field needs to be added as a SPFieldLink and not as SPField itself since the field already exists in the root web. The below modified code is working fine for me.

var field = web.Site.RootWeb.AvailableFields[new Guid("<<FieldID>>")];
foreach (SPContentType cType in web.Lists["ListName"].ContentTypes)
{
    SPFieldLink fieldLink = new SPFieldLink(field);
    cType.FieldLinks.Add(fieldLink);
    cType.Update();
}

Hopefully this helps some one or may be myself in the future when I struggle with the same issue.

Thanks
Senthil S

4 comments:

  1. Very handy thanks :) Ironically I just forgot the cType.update!

    ReplyDelete
  2. I have the same error while editing field inside contenttype.
    SPField.Update() raises error.
    What should I do?

    ReplyDelete
    Replies
    1. Ivan,
      have you set the web.AllowUnsafeUpdates = true before trying to update?

      Delete
    2. Senthil, Thanks, I have already found the solution.
      The reason was SPField usage vs SPFieldLinks usage.
      http://gorbadei.blogspot.ru/2013/05/error-this-functionality-is-unavailable.html

      Delete