Defining SharePoint Content Types in Code

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.spcontenttype.fieldlinks.aspx


Posted

in

by

Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.