Create Content Type using ECMA Script

Leave a Comment
Hi All,
In a following post, we will see how to Create Content Type by using ECMA Script and setting Properties of the Content Type like Description,Group Name etc.,
In a following example I am setting Parent Content Type as “Item”. You can find the same from the Code.

Controls in my “.aspx” Page.

<div>
    <p id="message">
        <!-- The following content will be replaced with the user name when you run the app - see App.js -->
        <input type="text" id="txtContentTypeName" />
        <br />
        <input type="button" id="btnCreate" value="Create" />
    </p>
</div>
Code in App.JS
    'use strict';
    var SPAppWebUrl;
    var spHostUrl;
    var contentTypeCollection;
    var pcontentType;
    (function () {
        // This code runs when the DOM is ready and creates a context object which is
        // needed to use the SharePoint object model
        $(document).ready(function () {
            spHostUrl = decodeURIComponent(getQueryStringParameter('SPHostUrl'));
            SPAppWebUrl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
            $('#btnCreate').on('click', function () {
                CreateContentTypes();
            });
        });
        function CreateContentTypes() {
            //reading the value from the Textbox
            var name = $('#txtContentTypeName').val();
            var Context = new SP.ClientContext.get_current();
            if (Context !== undefined && Context !== null) {
                var parentContext = new SP.AppContextSite(Context, spHostUrl);
                var web = parentContext.get_web();
                contentTypeCollection = web.get_contentTypes();
                Context.load(contentTypeCollection);
                Context.executeQueryAsync(Function.createDelegate(this, onQuerySucceeded),
                                                Function.createDelegate(this, onQueryFailed));
            }
            function onQuerySucceeded() {
                //checking whether the content type is already existed with same name
                var isExisted = false;
                var contentEnumerator = contentTypeCollection.getEnumerator();
                var exContentType;
                while (contentEnumerator.moveNext()) {
                    var currentCT = contentEnumerator.get_current();
                    if (currentCT.get_name() == name) {
                        isExisted = true;
                        break;
                    }
                }
                if (isExisted) {
                    alert('Content Type is alredy Existed');
                }
                else {
                    pcontentType = contentTypeCollection.getById('0x01');
                    //Creating the New Content Type
                    var newContentType = new SP.ContentTypeCreationInformation();
                    //Setting the Properties - START******
                    newContentType.set_name(name);
                    //Setting Description of Content Type
                    newContentType.set_description('My custom content type');
                    //Setting Parent Content Type
                    newContentType.set_parentContentType(pcontentType);
                    //Setting Group
                    newContentType.set_group('SPKitchen');
                    //Setting the Properties - END******
                    //Adding our new Content Type to Content type Collection.
                    contentTypeCollection.add(newContentType);

                    Context.load(contentTypeCollection);
                    Context.executeQueryAsync(Function.createDelegate(this, onCreationSucceeded),
                    Function.createDelegate(this, onQueryFailed));
                }
            }
            function onCreationSucceeded() {
                alert('Content Type Created Successfully');
            }
            function onQueryFailed(sender, args) {
                alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
            }
        }
        function getQueryStringParameter(urlParameterKey) {
            var params = document.URL.split('?')[1].split('&');
            var strParams = '';
            for (var i = 0; i < params.length; i = i + 1) {
                var singleParam = params[i].split('=');
                if (singleParam[0] == urlParameterKey)
                    return decodeURIComponent(singleParam[1]);
            }
        }
    })();
We Can see the Output as follows,
Success Message after Creation.

We can find the created Content Type under Site Settings ->Content Types.


Note: The above Code is written and executed in App Model, We can use the same in our regular development also.

Thanks.

Related Post

0 comments:

Post a Comment