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
Very handy thanks :) Ironically I just forgot the cType.update!
ReplyDeleteI have the same error while editing field inside contenttype.
ReplyDeleteSPField.Update() raises error.
What should I do?
Ivan,
Deletehave you set the web.AllowUnsafeUpdates = true before trying to update?
Senthil, Thanks, I have already found the solution.
DeleteThe reason was SPField usage vs SPFieldLinks usage.
http://gorbadei.blogspot.ru/2013/05/error-this-functionality-is-unavailable.html