Creating a Content Type Using Code

Ratings:
(4)
Views:0
Banner-Img
  • Share this blog:

Content-Type Using Code

As an alternative to using declarative XML to create a content type, you can use the SharePoint Foundation object model. Typically, declarative XML is easier to write. However, declarative XML generally offers less flexibility than the object model, which has access to the capabilities of the entire Microsoft .NET Framework and can be debugged at run time. Both approaches are supported by templates provided with SharePoint development tools in Microsoft Visual Studio 2010. Place the code that defines your content type in the FeatureActivated method of a subclass of the SPFeatureReceiverclass. You create a content type by calling the constructor for the SPContentType class. Before you call the constructor, you must gather three items to pass as arguments:

Learn SharePoint by Tekslate - Fastest growing sector in the industry. Explore Online "SharePoint Training" and course is aligned with industry needs & developed by industry veterans. Tekslate will turn you into a SharePoint Expert.

 

  • AnSPContentType object that represents the parent content type.

You can retrieve this object from the collection returned in the AvailableContentTypes property of the SPWebobject that represents the website where you are creating your content type.

  • AnSPContentTypeCollection object that represents the collection for the website where you are creating the content type.

You can get this object by accessing the ContentTypes property of the SPWeb object that represents the website where you are creating the content type.

  • A string that contains the name that you want to give the content type.

The name that you provide is used as the content type's display name. Some characters are not allowed in content type names. You can validate your proposed name by calling the static method ValidateName(String). This method checks for illegal characters but does not check for duplicate names. After you call the constructor to create a new SPContentType object, you must add it to the website's content type collection in a separate call to the Add(SPContentType) method of the SPContentTypeCollection object that represents the website's collection. This step completes the initialization of the content type.

The Add(SPContentType) method throws an SPException exception if a content type with the same name already exists in the collection.

If you intend to set properties of the content type, you should save the SPContentType object that is returned by the Add method. You can add columns to the content type by referencing each column in a SPFieldLink object. Then call theAdd(SPFieldLink) method of the SPFieldLinkCollection object that is returned by the content type's FieldLinks property. When you have completed the content type's configuration, call the Update() method to commit the changes to the database.

Example 2

The following example creates exactly the same site columns and content types as are created by the previous example. The only difference is that instead of using declarative XML, this example uses code in theFeatureActivated method of a feature receiver. The properties parameter of the FeatureActivated method is a SPFeatureReceiverProperties object. The Featureproperty of this object returns an SPFeature object that has a Parent property that contains a boxed SPSite object or a boxed SPWeb object. You should not dispose of these objects. However, you should dispose of any new SPWeb orSPSite objects that your code creates. For more information, see Disposing Objects.

public override void FeatureActivated(SPFeatureReceiverProperties properties) { SPWeb web = null; if (properties.Feature.Parent is SPSite) { SPSite sites = (SPSite)properties.Feature.Parent; web = sites.RootWeb; } else { web = (SPWeb)properties.Feature.Parent; } if (web == null) return; /* CREATE SITE COLUMNS */ string columnGroup = "Financial Columns"; // Amount string amountFieldName = web.Fields.Add("Amount", SPFieldType.Currency, false); SPFieldCurrency amountField = (SPFieldCurrency)web.Fields.GetFieldByInternalName(amountFieldName); amountField.Group = columnGroup; amountField.DisplayFormat = SPNumberFormatTypes.TwoDecimals; amountField.MinimumValue = 0; amountField.Update(); // Client Name string clientFieldName = web.Fields.Add("Client Name", SPFieldType.Text, false); SPFieldText clientField = (SPFieldText)web.Fields.GetFieldByInternalName(clientFieldName); clientField.Group = columnGroup; clientField.Update(); // Date Opened string dateOpenedFieldName = web.Fields.Add("Date Opened", SPFieldType.DateTime, false); SPFieldDateTime dateOpenedField = (SPFieldDateTime)web.Fields.GetFieldByInternalName(dateOpenedFieldName); dateOpenedField.Group = columnGroup; dateOpenedField.DisplayFormat = SPDateTimeFieldFormatType.DateOnly; dateOpenedField.DefaultValue = "[today]"; dateOpenedField.Update(); // Cost Center Name string costCenterFieldName = web.Fields.Add("Cost Center", SPFieldType.Choice, false); SPFieldChoice costCenterField = (SPFieldChoice)web.Fields.GetFieldByInternalName(costCenterFieldName); costCenterField.Choices.Add("Administration"); costCenterField.Choices.Add("Information Services"); costCenterField.Choices.Add("Facilities"); costCenterField.Choices.Add("Operations"); costCenterField.Choices.Add("Sales"); costCenterField.Choices.Add("Marketing"); costCenterField.Group = columnGroup; costCenterField.Update(); /* CREATE SITE CONTENT TYPES */ string contentTypeGroup = "Financial Content Types"; // Get a content type to be the parent of a new Financial Document content type. SPContentType documentCType = web.AvailableContentTypes[SPBuiltInContentTypeId.Document]; // Create the Financial Document content type. SPContentType financialDocumentCType = new SPContentType(documentCType, web.ContentTypes, "Financial Document"); // Note: A content type is not initialized until after it is added. financialDocumentCType = web.ContentTypes.Add(financialDocumentCType); financialDocumentCType.Group = contentTypeGroup; // Add the Date Opened column. Child content types inherit the column. SPFieldLink dateOpenedFieldRef = new SPFieldLink(dateOpenedField); dateOpenedFieldRef.Required = true; financialDocumentCType.FieldLinks.Add(dateOpenedFieldRef); // Add the Amount column. Child content types inherit the column. SPFieldLink amountFieldRef = new SPFieldLink(amountField); financialDocumentCType.FieldLinks.Add(amountFieldRef); // Commit changes. financialDocumentCType.Update(); // Create the Invoice content type. SPContentType invoiceCType = new SPContentType(financialDocumentCType, web.ContentTypes, "Invoice"); invoiceCType = web.ContentTypes.Add(invoiceCType); invoiceCType.Group = contentTypeGroup; // Modify the Title column inherited from the parent. SPFieldLink serviceFieldRef = invoiceCType.FieldLinks[SPBuiltInFieldId.Title]; serviceFieldRef.DisplayName = "Service"; serviceFieldRef.Required = true; // Add the Client column. SPFieldLink clientFieldRef = new SPFieldLink(clientField); clientFieldRef.Required = true; invoiceCType.FieldLinks.Add(clientFieldRef); // Specify a document template. invoiceCType.DocumentTemplate = "Invoice.docx"; // Commit changes. invoiceCType.Update(); // Create the Purchase Order content type. SPContentType purchaseOrderCType = new SPContentType(financialDocumentCType, web.ContentTypes, "Purchase Order"); purchaseOrderCType = web.ContentTypes.Add(purchaseOrderCType); purchaseOrderCType.Group = contentTypeGroup; // Modify the Title column inherited from the parent. SPFieldLink itemFieldRef = purchaseOrderCType.FieldLinks[SPBuiltInFieldId.Title]; itemFieldRef.DisplayName = "Item"; itemFieldRef.Required = true; // Add the Department column. SPFieldLink departmentFieldRef = new SPFieldLink(costCenterField); departmentFieldRef.DisplayName = "Department"; departmentFieldRef.Required = true; purchaseOrderCType.FieldLinks.Add(departmentFieldRef); // Specify a document template. purchaseOrderCType.DocumentTemplate = "PurchaseOrder.docx"; // Commit changes. purchaseOrderCType.Update();}

  Rules of Assignment

The three most important built-in content types are Item, Document, and Folder. The reason these three types are important is that SharePoint Foundation enforces certain rules about how content types that are derived from them can be used. You can assign content types to list items, documents, and folders. However, any content type that you assign to a document library must inherit from Document or from a content type derived from Document. Moreover, any content type that you assign to a list must not derive from Document. The exception to this pair of rules is the Folder content type and its derivatives. Folders can exist on both lists and document libraries.

About Author
Authorlogo
Name
TekSlate
Author Bio

TekSlate is the best online training provider in delivering world-class IT skills to individuals and corporates from all parts of the globe. We are proven experts in accumulating every need of an IT skills upgrade aspirant and have delivered excellent services. We aim to bring you all the essentials to learn and master new technologies in the market with our articles, blogs, and videos. Build your career success with us, enhancing most in-demand skills in the market.


Stay Updated


Get stories of change makers and innovators from the startup ecosystem in your inbox