Implementation
- Get Host Web Context
- Get Site Content Types Collection
- Define new Content Type
- Add the new Content Type to collection
Get Started:
- Create a SharePoint –hosted ‘Apps for SharePoint 2013’ project using Visual Studio 2012/2013.
- Provide required permission to App for creating Content Type in AppManifest.xml.
- Add a button on page to create Content Type.
- <%-- The markup and script in the following Content element will be placed in the <body> of the page --%>
- <asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
- <div>
- <input type="button" id="btnCreateContent Type" value="Create Content Type" onclick="createContentType()" />
- </div>
- </asp:Content>
- Modify App.js file and replace its content by the following code.
- 'use strict';
-
- var context = SP.ClientContext.get_current();
- var hostWebUrl, hostWebContext;
-
-
- $(document).ready(function () {
-
- hostWebUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
- hostWebContext = new SP.AppContextSite(context, hostWebUrl);
- });
-
-
- function getQueryStringParameter(paramToRetrieve) {
- var params = document.URL.split("?")[1].split("&");
- for (var i = 0; i < params.length; i = i + 1) {
- var singleParam = params[i].split("=");
- if (singleParam[0] == paramToRetrieve) return singleParam[1];
- }
- }
-
-
- function createContentType() {
- if (hostWebContext != undefined && hostWebContext != null) {
- var hostWeb = hostWebContext.get_web();
- var contentTypeCollection = hostWeb.get_contentTypes();
-
-
-
- var contentType = contentTypeCollection.getById("0x0101");
-
- var newContentType = new SP.ContentTypeCreationInformation();
- newContentType.set_name('Employee');
- newContentType.set_group('Employee Details');
- newContentType.set_description('Content Type for Employee Details.');
-
- newContentType.set_parentContentType(contentType);
- contentTypeCollection.add(newContentType);
- context.load(contentTypeCollection);
- context.executeQueryAsync(
- function () {
- alert('Content type created successfully on Host Web.');
- },
- function onContenttypeFailed(sender, args) {
- alert('Content type creation failed. Error: ' + args.get_message() + '\n' + args.get_stackTrace());
- });
- }
- }
- Build and Deploy the solution.
- Click on ‘Create Content Type’ button, Content Type will be created on Host Web.
- Navigate to Host Web Site Content types, you will see ‘Employee’ Content Type under ‘Employee Details’ group.
Additional Data
The following table shows Content Type Ids, which can be used as Base Content Type.
Hierarchy:
Conclusion
Using this JSOM, you can create Content Type on Host Web. By using only App Web context, you can create Content type on App Web. To use any other Content type as Base Content type, you can refer to the above table. If you do not provide any base Content type, by default it is set to ‘Item’ Content type.