Tags

, , ,

For each operation you perform on SharePoint list using JavaScript client object model, client context is required to execute query asynchronous operation. But this doesn’t mean is an equal sign between what I have just called it operation and, as an example, each item you want to add to SharePoint list. You can add multiple items to the list and execute client context operation only once.

As in general I like JavaScript organized code, I have created a small file, presented below, which for the moment requires only jQuery to be loaded. There is a plan to extend it and integrate it into a bigger project, but for this example is sufficient to copy the code below only.

/// <Reference Name="MicrosoftAjax.js" />
/// <Reference Path="../jQuery/jquery.js" />



(function () {

    var scriptName = 'SharePoint';


    function execute() {

        Type.registerNamespace('Sys.SharePoint');
        

        Sys.SharePoint.Data = function () {
            /// <summary>Sys.SharePoint.Data static class</summary>
            throw 'Cannot initialize Sys.SharePoint.Data static class';
        }        


        Sys.SharePoint.Data.AddItems = function (listName, listItems, web, success, fail) {
            /// <signature>
            ///     <summary>Add items to the list</summary>
            ///     <param name="listName" type="String" mayBeNull="false" optional="false">List name</param>
            ///     <param name="listItems" type="Array" mayBeNull="false" optional="false" elementType="Object" elementMayBeNull="false">List items</param>
            ///     <param type="SP.Web" mayBeNull="false" optional="true">Web</param>
            /// </signature>
            /// <signature>
            ///     <summary>Add items to the list</summary>
            ///     <param name="listName" type="String" mayBeNull="false" optional="false">List name</param>
            ///     <param name="listItems" type="Array" mayBeNull="false" optional="false" elementType="Object" elementMayBeNull="false">List items</param>
            ///     <param name="web" type="SP.Web" mayBeNull="true" optional="false">Web</param>
            ///     <param name="success" type="Function" mayBeNull="false" optional="false">Success</param>
            ///     <param name="fail" type="Function" mayBeNull="false" optional="true">Fail</param>
            /// </signature>
            var e1 = Function.validateParameters(arguments, [{ name: 'listName', type: String, mayBeNull: false, optional: false },
                                                             { name: 'listItems', type: Array, mayBeNull: false, optional: false, elementType: Object, elementMayBeNull: false },
                                                             { name: 'web', type: SP.Web, mayBeNull: false, optional: true }], true);
            var e2 = Function.validateParameters(arguments, [{ name: 'listName', type: String, mayBeNull: false, optional: false },
                                                             { name: 'listItems', type: Array, mayBeNull: false, optional: false, elementType: Object, elementMayBeNull: false },
                                                             { name: 'web', type: SP.Web, mayBeNull: true, optional: false },
                                                             { name: 'success', type: Function, mayBeNull: false, optional: false },
                                                             { name: 'fail', type: Function, mayBeNull: false, optional: true }], true);
            if (e1 !== null && e2 !== null)
                throw 'Invalid parameters calling AddItems';

            // Define context and web objects for operations
            var ctx = (typeof web === 'undefined' || web === null) ? SP.ClientContext.get_current() : web.get_context();
            var web = (typeof web === 'undefined' || web === null) ? ctx.get_web() : web;

            // Use jQuery deffered for operation
            if (e1 === null && e2 !== null) {
                return Sys.SharePoint.Data._defferedAddItems(listName, listItems, ctx, web);
            }

            // Choose success and fail methods to be executed when operation is ready
            if (e1 !== null && e2 === null) {
                var fail = fail || function (err) { alert(err); };
                Sys.SharePoint.Data._nonDefferedAddItems(listName, listItems, ctx, web, success, fail);
            }

            return null;
        }


        Sys.SharePoint.Data._defferedAddItems = function (listName, listItems, ctx, web) {
            /// <summary>Add items to the list using jQuery deffered (internal use)</summary>
            /// <param name="listName" type="String" mayBeNull="false" optional="false">List name</param>
            /// <param name="listItems" type="Array" mayBeNull="false" optional="false" elementType="Object" elementMayBeNull="false">List items</param>
            /// <param name="ctx" type="SP.ClientContext" mayBeNull="false" optional="false">Context</param>
            /// <param name="web" type="SP.Web" mayBeNull="false" optional="false">Web</param>

            var oList = web.get_lists().getByTitle(listName);
            var deffered = jQuery.Deferred();
            var results = [];


            // for each item of in list items we create item in SharePoint list
            for (var i = 0; i < listItems.length; i++) {

                var listItem = listItems[i];
                var listItemCreationInfo = new SP.ListItemCreationInformation();
                var oListItem = oList.addItem(listItemCreationInfo);

                // for each property of current item, we assign field values
                for (var field in listItem) {
                    oListItem.set_item(field, listItem[field]);
                }

                // update and load SharePoint list item and add it to results array
                oListItem.update();
                ctx.load(oListItem);
                results.push(oListItem);
            }


            // context will execute query async
            ctx.executeQueryAsync(function () {
                deffered.resolve(results);
            }, function (sender, args) {
                deffered.reject(args.get_message());
            });

            return deffered.promise();
        }

        Sys.SharePoint.Data._nonDefferedAddItems = function (listName, listItems, ctx, web, success, fail) {
            /// <summary>Add items to the list (internal use)</summary>
            /// <param name="listName" type="String" mayBeNull="false" optional="false">List name</param>
            /// <param name="listItems" type="Array" mayBeNull="false" optional="false" elementType="Object" elementMayBeNull="false">List items</param>
            /// <param name="ctx" type="SP.ClientContext" mayBeNull="false" optional="true">Context</param>
            /// <param name="web" type="SP.Web" mayBeNull="false" optional="false">Web</param>
            /// <param name="success" type="Function" mayBeNull="false" optional="false">Success</param>   
            /// <param name="fail" type="Function" mayBeNull="false" optional="false">Fail</param>   

            var oList = web.get_lists().getByTitle(listName);
            var results = [];


            // for each item of in list items we create item in SharePoint list
            for (var i = 0; i < listItems.length; i++) {

                var listItem = listItems[i];
                var listItemCreationInfo = new SP.ListItemCreationInformation();
                var oListItem = oList.addItem(listItemCreationInfo);

                // for each property of current item, we assign field values
                for (var field in listItem) {
                    oListItem.set_item(field, listItem[field]);
                }

                // update and load SharePoint list item and add it to results array
                oListItem.update();
                ctx.load(oListItem);
                results.push(oListItem);
            }

            // context will execute query async
            ctx.executeQueryAsync(function () {
                success(results);
            }, function (sender, args) {
                fail(args.get_message());
            });
        }


        Sys.SharePoint.Data.registerClass('Sys.SharePoint.Data');

    }

    

    if (window.Sys && Sys.loader) {
        Sys.loader.registerScript(scriptName, null, execute);
    }
    else {
        execute();
    }


})();

Deffered operation

Let’s take a look at the following example.

	var items = [];
	items.push({ Title: 'Title 1' });
	items.push({ Title: 'Title 2' });
	items.push({ Title: 'Title 3' });
	
	var addItems = Sys.SharePoint.Data.AddItems('List Name', items);
	
	addItems.fail(function(error) {
		alert(fail);
	});
	
	addItems.done(function(results) {
		alert('Success');
	});

You can notice I have used an object for each item I wanted to create and properties have the same name as internal fields. I have add them to an array and pass it as a parameter to Sys.SharePoint.Data.AddItems method. And instead of using classic example, I have used jQuery deffered object to write code easier.

If web parameter is not specified, the web for current context is used. However, it can be specified as additional parameter.

	var context = new SP.ClientContext("https://mydomain.com/sites/toolkit");
	var web = context.get_web();
	
	
	var items = [];
	items.push({ Title: 'Title 13' });
	items.push({ Title: 'Title 12' });
	items.push({ Title: 'Title 10' });
	
	var addItems = Sys.SharePoint.Data.AddItems('List Name', items, web);
	
	addItems.fail(function(error) {
		alert(fail);
	});
	
	addItems.done(function(results) {
		alert('Success');
	});

Classic way

However, you may prefer to use the classic way and pass success and fail callback functions as parameters.

	var context = new SP.ClientContext("https://mydomain.com/sites/toolkit");
	var web = context.get_web();
	
	
	var success = function(results) {
		alert('Operation completed and insert ' + results.length + ' items');
		alert('First item title is ' + results[0].get_item('Title'));
		
	}
	
	
	var fail = function(error) {
		alert(error);
	}
	
	
	var items = [];
	items.push({ Title: 'Title 100' });
	items.push({ Title: 'Title 101' });
	items.push({ Title: 'Title 102' });
	
	Sys.SharePoint.Data.AddItems('List Name', items, web, success, fail);

Conclusion

Sys.SharePoint.Data.AddItems is a method with two signatures. If you want to use jQuery.Deffered object to work with results, you need pass these parameters

  • listName as string and mandatory
  • listItems as array of objects (not null and not optional)
  • web as SP.Web (not null but optional). If not specified, it is considered to be web for current client context.

The second signature accepts five parameters.

  • listName as string and mandatory
  • listItems as array of objects (not null and not optional)
  • web as SP.Web (can be null, but not optional). If not specified, it is considered to be web for current client context.
  • success as function (not null and not optional). It should accept as parameter an array containing created items.
  • fail as function (not null, but optional). It should accept as a parameter a string representing error message.
Advertisements