Skip to main content

Cloud

Creating a content type in SharePoint programmatically using the object model

Continuing a series of posts with examples for provisioning SharePoint elements through an object model, here is an example of how to create a content type using an object model:

public static SPContentType CreateContentType(SPWeb web, string contentTypeName, List<SPField> columns)

{

//create an empty content type and add it to content type collection

SPContentType contentType = new SPContentType(web.AvailableContentTypes["Item"], web.ContentTypes, contentTypeName);

contentType.Group = groupName;

web.ContentTypes.Add(contentType);

//add columns from the list to the content type

foreach (SPField column in columns)

{

SPFieldLink fieldLink = new SPFieldLink(column);

contentType.FieldLinks.Add(fieldLink);

}

contentType.Update();

web.Update();

return contentType;

}

If you need to set up your own application pages as custom forms for this content type, you can use the follwing method. Keep in mind that using XmlDocuments property of the SPContentTpe will set these pages up also but it will ONLY work if you create SPList through the web interface. If you need to prov ision the list instance programmatically through object model, the list will continue using standard forms. Therefore it is recommened that you use DisplayFormUrl, EditFormUrl, and NewFormUrl properties insdetad of XmlDocuments property.

public static void SetContentTypeCustomForms(SPContentType contentType, string newFormUrl, string editFormUrl, string displayFormUrl)

{

//explicitly set the forms

contentType.DisplayFormUrl = displayFormUrl;

contentType.EditFormUrl = editFormUrl;

contentType.NewFormUrl = newFormUrl;

contentType.Update();

contentType.ParentWeb.Update();

}

As always, if you see any mistakes or inaccuracies in this blog, please let me know.

Leave a Reply

Your email address will not be published. Required fields are marked *

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

PointBridge Blogs

More from this Author

Follow Us
TwitterLinkedinFacebookYoutubeInstagram