Defining SharePoint Content Types in Code
Dimitri Dhuyvetter - Thu, 12/03/2009 - 15:52
The sample code on Defining SharePoint Content Types in Code posted on "Wrox Article : Creating Content Type Metadata for SharePoint 2007 Document Management Solutions : Page 2 - Wrox" contains an error.
The sample code is:
using (SPSite site = new SPSite("http://localhost")) { using (SPWeb web = site.OpenWeb()) { SPContentType baseType = web.AvailableContentTypes["Document"]; SPContentType proposal = new SPContentType( baseType, web.ContentTypes, "Project Proposal"); web.ContentTypes.Add(proposal); proposal.FieldLinks.Add(new SPFieldLink(web.AvailableFields["Author"])); } }
But this won't work. First of all, there is no proposal.Update() to commit the changes and if there was, ytou would get an error since SPWeb.AvailableContentTypes is a read-only collection, so you can't update the SPContentType you get that way.
The correct code should be
using (SPSite site = new SPSite("http://localhost")) { using (SPWeb web = site.OpenWeb()) { SPContentType baseType = web.ContentTypes["Document"]; SPContentType proposal = new SPContentType( baseType, web.ContentTypes, "Project Proposal"); web.ContentTypes.Add(proposal); proposal.FieldLinks.Add(new SPFieldLink(web.AvailableFields["Author"])); proposal.Update(); } }
More info on SPContentType.FieldLinks on http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spcontentty...
-
- Dimitri Dhuyvetter's blog
- Login or register to post comments
