none
[FORUM FAQ] Step by Step JSOM in SharePoint - Code Samples RRS feed

  • General discussion

  • Overview

    The ECMAScript (JavaScript, JScript) object model was introduced in Microsoft SharePoint Foundation 2010, all code is executed asynchronously and relies on callback functions to work with objects inside of SharePoint. What's more, we can use Include statements and the load (clientObject) function to load the object properties needed to minimize stress on the server.

    In the following demos, we will demonstrate how to work with ClientContext, Web, List, User and Group, all the samples below will be executed in such a script:

    <script type="text/javascript" src="/SiteAssets/jquery-1.10.2.min.js"></script>
    <script type="text/javascript">
    
    // When the body is loaded, the onload event handler executes each function whose name is contained in this array.
    _spBodyOnLoadFunctionNames.push("callCSOM");
    
    function callCSOM()
    {
    	$("#Button1").click(function()
    	{
    		// Make sure the SharePoint script file 'sp.js' is loaded before your code runs.
    		ExecuteOrDelayUntilScriptLoaded(sharePointReady, "sp.js");
    	});	
    }
    
    function sharePointReady() 
    {
    	customFunction(); 
    }
    
    function customFunction()
    {
    	//write the custom methods here
    }
    
    </script>
    <input id="Button1" type="button" value="Run Code"/>
    <p/>
    <div id="div1">test</div>

    You can test the samples below by putting them into the "sharePointReady" function. 


    Get Started

    Sample 1. 
    Retrieve the current SP.Web object: Use the ClientContext class to return context information about objects such as the current web application, site, site collection, or server version. 

    <script type="text/javascript" src="/SiteAssets/jquery-1.10.2.min.js"></script>
    <script type="text/javascript">
    
    // When the body is loaded, the onload event handler executes each function whose name is contained in this array.
    _spBodyOnLoadFunctionNames.push("callCSOM");
    
    function callCSOM()
    {
    	$("#Button1").click(function()
    	{
    		// Make sure the SharePoint script file 'sp.js' is loaded before your code runs.
    		ExecuteOrDelayUntilScriptLoaded(sharePointReady, "sp.js");
    	});	
    }
    
    function sharePointReady() 
    {
    	getCurrentWeb();
    }
    
    var clientContext;
    var targetWeb;
    var message = "Web retrieved:";
    
    function getCurrentWeb()
    {
        // Create an instance of the current context to return context information
        clientContext = SP.ClientContext.get_current();
        targetWeb = clientContext.get_web();
    
        //Retrieves an enumerable sequence of the child client objects from a collection
        clientContext.load(targetWeb);
    
        //Executes the current pending request asynchronously on the server
        clientContext.executeQueryAsync(onRequestSucceeded, onRequestFailed);
    }
    
    //the delegate of the method that is called when the request is executed successfully
    function onRequestSucceeded() 
    {
    	//retrieve the properties of Web
        message += "___Title: " + targetWeb.get_title();
        message += "___ID: " + targetWeb.get_id();
        message += "___Language: " + targetWeb.get_language();
        message += "___UI Version: " + targetWeb.get_uiVersion();
        message += "___Description: " + targetWeb.get_description();
        message += "___Created: " + targetWeb.get_created();
    
        $("#div1").text(message);   
    }
    
    //the delegate of the method that is called when the request is executed unsuccessfully
    function onRequestFailed(sender, args) 
    {
        alert('Error: ' + args.get_message());
    }
    </script>
    <input id="Button1" type="button" value="Run Code"/>
    <p/>
    <div id="div1">test</div>

    Reference:
    SP.ClientContext Class
    http://msdn.microsoft.com/en-us/library/office/ff408569(v=office.14).aspx
    SP.Web Class
    http://msdn.microsoft.com/en-us/library/office/ff410960(v=office.14).aspx

    Sample 2. 
    Gets the current user of the site: The demo below will show how to retrieve the currentUser properties of the current site, then retrieve the properties of the current user.

    <script type="text/javascript" src="/SiteAssets/jquery-1.10.2.min.js"></script>
    <script type="text/javascript">
    
    // When the body is loaded, the onload event handler executes each function whose name is contained in this array.
    _spBodyOnLoadFunctionNames.push("callCSOM");
    
    function callCSOM()
    {
        $("#Button1").click(function()
        {
            // Make sure the SharePoint script file 'sp.js' is loaded before your code runs.
            ExecuteOrDelayUntilScriptLoaded(sharePointReady, "sp.js");
        }); 
    }
    
    function sharePointReady() 
    {
        getCurrentUser();
    }
    
    var clientContext;
    var currentUser;
    var targetWeb;
    var message = "Web retrieved:";
    
    function getCurrentUser()
    {
        // Create an instance of the current context to return context information
        clientContext = SP.ClientContext.get_current();
        this.website = clientContext.get_web();
        this.currentUser = website.get_currentUser();
        clientContext.load(currentUser);
    
        //Executes the current pending request asynchronously on the server
        clientContext.executeQueryAsync(onRequestSucceeded, onRequestFailed);
    }
    
    //the delegate of the method that is called when the request is executed successfully
    function onRequestSucceeded() 
    {
        //retrieve the properties of SP.User
        message += "___Title: " + currentUser.get_title();
        message += "___id: " + currentUser.get_id();
        message += "___loginName: " + currentUser.get_loginName();
        message += "___principalType: " + currentUser.get_principalType();
    
        $("#div1").text(message);   
    }
    
    //the delegate of the method that is called when the request is executed unsuccessfully
    function onRequestFailed(sender, args) 
    {
        alert('Error: ' + args.get_message());
    }
    </script>
    <input id="Button1" type="button" value="Run Code"/>
    <p/>
    <div id="div1">test</div>

    Reference:
    SP.Web.currentUser Property
    http://msdn.microsoft.com/en-us/library/office/ee553760(v=office.14).aspx
    SP.Principal Properties
    http://msdn.microsoft.com/en-us/library/office/ee554498(v=office.14).aspx


    Sample 3. 

    Gets list items of a list: The demo below will show how to use CAML statement to query the top 100 items of a list. At first, we take use of SP.CamlQuery class to composite our query statement, then use 
    SP.List.getItems(CamlQuery) to retrievea collection of items from this list.

    <script type="text/javascript" src="/SiteAssets/jquery-1.10.2.min.js"></script>
    <script type="text/javascript">
    
    // When the body is loaded, the onload event handler executes each function whose name is contained in this array.
    _spBodyOnLoadFunctionNames.push("callCSOM");
    
    function callCSOM()
    {
        $("#Button1").click(function()
        {
            // Make sure the SharePoint script file 'sp.js' is loaded before your code runs.
            ExecuteOrDelayUntilScriptLoaded(sharePointReady, "sp.js");
        }); 
    }
    
    function sharePointReady() 
    {
    	getListItems();
    }
    
    var clientContext;
    var currentUser;
    var targetWeb;
    var message = "Web retrieved:";
    
    function getListItems()
    {
        // Create an instance of the current context to return context information
        clientContext = SP.ClientContext.get_current();
    
        //Returns the list with the specified title from the collection
        var oList = clientContext.get_web().get_lists().getByTitle('list');
    
        //use CAML to query the top 100 items
        var camlQuery = new SP.CamlQuery();
    
        //sets value that specifies the XML schema that defines the list view
        camlQuery.set_viewXml('<View><RowLimit>100</RowLimit></View>');
    
        //Returns a collection of items from the list based on the specified query
        this.collListItem = oList.getItems(camlQuery);
    
        clientContext.load(collListItem);
        clientContext.executeQueryAsync(onRequestSucceeded, onRequestFailed);
    }
    
    //the delegate of the method that is called when the request is executed successfully
    function onRequestSucceeded() 
    {
    	//Returns an enumerator to iterate through the collection
        var listItemEnumerator = collListItem.getEnumerator();
            
        //Advances the enumerator to the next element of the collection    
        while (listItemEnumerator.moveNext()) 
        {   
        	//Gets the current element in the collection
            var oListItem = listItemEnumerator.get_current();
            message += '___'+'Title: ' + oListItem.get_item('Title');
            message += '___'+'ID: ' + oListItem.get_item('ID');
            message += '________________________________________________';
        }
    
        $("#div1").text(message);   
    }
    
    //the delegate of the method that is called when the request is executed unsuccessfully
    function onRequestFailed(sender, args) 
    {
        alert('Error: ' + args.get_message());
    }
    </script>
    <input id="Button1" type="button" value="Run Code"/>
    <p/>
    <div id="div1">test</div>

    Reference:
    SP.Web.lists Property
    http://msdn.microsoft.com/en-us/library/office/ee557490(v=office.14).aspx
    SP.ListCollection.getByTitle(strListName) Method
    http://msdn.microsoft.com/en-us/library/office/ee658474(v=office.14).aspx
    SP.CamlQuery.viewXml Property
    http://msdn.microsoft.com/en-us/library/office/ee549968(v=office.14).aspx
    SP.List.getItems(query_) Method
    http://msdn.microsoft.com/en-us/library/office/ee659349(v=office.14).aspx
    SPListItemCollection.GetEnumerator method 
    http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splistitemcollection.getenumerator.aspx
    IEnumerator.MoveNext Method 
    http://msdn.microsoft.com/EN-US/library/system.collections.ienumerator.movenext
    IEnumerator.Current Property 
    http://msdn.microsoft.com/EN-US/library/system.collections.ienumerator.current


    Sample 4. 
    Add items in a list: We need to Initialize a instance of the SP.ListItemCreationInformation Class, then use the SP.List.addItem(ListItemCreationInformation) function to create a new list item in the list,
    then we can set the values of fields by using the Item property of SP.ListItem.

    <script type="text/javascript" src="/SiteAssets/jquery-1.10.2.min.js"></script>
    <script type="text/javascript">
    
    // When the body is loaded, the onload event handler executes each function whose name is contained in this array.
    _spBodyOnLoadFunctionNames.push("callCSOM");
    
    function callCSOM()
    {
        $("#Button1").click(function()
        {
            // Make sure the SharePoint script file 'sp.js' is loaded before your code runs.
            ExecuteOrDelayUntilScriptLoaded(sharePointReady, "sp.js");
        }); 
    }
    
    function sharePointReady() 
    {
        addListItems();
    }
    
    var clientContext;
    var currentUser;
    var targetWeb;
    var message = "Web retrieved:";
    
    function addListItems()
    {
        // Create an instance of the current context to return context information
        clientContext = SP.ClientContext.get_current();
        var oList = clientContext.get_web().get_lists().getByTitle('list');
    
        //Initializes a new instance of the SP.ListItemCreationInformation Class
        var itemCreateInfo = new SP.ListItemCreationInformation();
    
        //Creates a new list item in the list
        this.newListItem = oList.addItem(itemCreateInfo);
    
        //Sets the specified field value
        newListItem.set_item('Title', 'new item here');
    
        //Commits changed properties of the list item
        newListItem.update();
        clientContext.load(newListItem);
    
        //Executes the current pending request asynchronously on the server
        clientContext.executeQueryAsync(onRequestSucceeded, onRequestFailed);
    }
    
    //the delegate of the method that is called when the request is executed successfully
    function onRequestSucceeded() 
    {
        message += '___'+'Title: ' + newListItem.get_item('Title');
        message += '___'+'ID: ' + newListItem.get_item('ID');
    
        
        $("#div1").text(message);   
    }
    
    //the delegate of the method that is called when the request is executed unsuccessfully
    function onRequestFailed(sender, args) 
    {
        alert('Error: ' + args.get_message());
    }
    </script>
    <input id="Button1" type="button" value="Run Code"/>
    <p/>
    <div id="div1">test</div>

    Reference:
    SP.List Methods
    http://msdn.microsoft.com/en-us/library/office/ee554951%28v=office.14%29.aspx
    SP.ListItemCreationInformation() Constructor
    http://msdn.microsoft.com/en-us/library/office/ee658591(v=office.14).aspx
    SP.List.addItem(parameters) Method
    http://msdn.microsoft.com/en-us/library/office/ee658490(v=office.14).aspx
    SP.ListItem.update() Method
    http://msdn.microsoft.com/en-us/library/office/ee659277(v=office.14).aspx


    Sample 5. 

    Delete items in a list with value of "Title" column is "new item here": At first, retrieve a collection of items with the value of "Title" column is "new item here" by using CamlQuery. Then iterate the 
    collection to retrieve the ids of these items. After that, we can use SP.List.getItemById() function to get the specific item and use SP.ListItem.deleteObject() to delete this item.

    <script type="text/javascript" src="/SiteAssets/jquery-1.10.2.min.js"></script>
    <script type="text/javascript">
    
    // When the body is loaded, the onload event handler executes each function whose name is contained in this array.
    _spBodyOnLoadFunctionNames.push("callCSOM");
    
    function callCSOM()
    {
        $("#Button1").click(function()
        {
            // Make sure the SharePoint script file 'sp.js' is loaded before your code runs.
            ExecuteOrDelayUntilScriptLoaded(sharePointReady, "sp.js");
        }); 
    }
    
    function sharePointReady() 
    {
        deleteListItems();
    }
    
    var clientContext;
    var oList;
    var message = "Web retrieved:";
    var count = 0;
    
    function deleteListItems()
    {
        // Create an instance of the current context to return context information
        clientContext = SP.ClientContext.get_current();
        oList = clientContext.get_web().get_lists().getByTitle('list');
        var camlQuery = new SP.CamlQuery();
        camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name="Title"/><Value Type="Text">new item here</Value></Eq></Where></Query></View>');
        this.collListItem = oList.getItems(camlQuery);   
        clientContext.load(oList);
        clientContext.load(collListItem);
    
        //Executes the current pending request asynchronously on the server
        clientContext.executeQueryAsync(onRequestSucceeded, onRequestFailed);
    }
    
    //the delegate of the method that is called when the request is executed successfully
    function onRequestSucceeded() 
    {
    	//stores all the id of the items in the current list for deleting
        var ary=new Array();
        var listItemEnumerator = collListItem.getEnumerator();
        while (listItemEnumerator.moveNext()) 
        {   
            count++;
            var oListItem = listItemEnumerator.get_current(); 
            message += '___'+'Title: ' + oListItem.get_item('Title');
            message += '___'+'ID: ' + oListItem.get_item('ID');
            ary.push(oListItem.get_item('ID'));
        }
        for(i in ary)
        {
            var item = oList.getItemById(ary[i]);
    
            //Deletes the list item
            item.deleteObject();
        }
        //Updates the database with changes that are made to the list
        oList.update();   
        clientContext.executeQueryAsync(onRequestSucceeded1, onRequestFailed1);
        
        $("#div1").text(message);   
    }
    
    //the delegate of the method that is called when the request is executed unsuccessfully
    function onRequestFailed(sender, args) 
    {
        alert('Error: ' + args.get_message());
    }
    
    function onRequestSucceeded1(sender, args) 
    {
        message+="---deleted "+count+" items";
        
        $("#div1").text(message);
    }
    
    function onRequestFailed1(sender, args) 
    {
        alert('Error: ' + args.get_message());
    }
    
    </script>
    <input id="Button1" type="button" value="Run Code"/>
    <p/>
    <div id="div1">test</div>

    Reference:
    SP.ListItem.deleteObject() Method
    http://msdn.microsoft.com/en-us/library/office/ee658907(v=office.14).aspx
    SP.List.update() Method
    http://msdn.microsoft.com/en-us/library/office/ee658925(v=office.14).aspx

    Sample 6. 
    Update the items with value of "Title" column is "new item here": In this demo, we use SP.ListItem.set_item() to update some fields value, then use SP.ListItem.update() to commit the changed properties of the list item.

    <script type="text/javascript" src="/SiteAssets/jquery-1.10.2.min.js"></script>
    <script type="text/javascript">
    
    // When the body is loaded, the onload event handler executes each function whose name is contained in this array.
    _spBodyOnLoadFunctionNames.push("callCSOM");
    
    function callCSOM()
    {
        $("#Button1").click(function()
        {
            // Make sure the SharePoint script file 'sp.js' is loaded before your code runs.
            ExecuteOrDelayUntilScriptLoaded(sharePointReady, "sp.js");
        }); 
    }
    
    function sharePointReady() 
    {
        updateListItems();
    }
    
    var clientContext;
    var oList;
    var message = "Web retrieved:";
    
    function updateListItems()
    {
        // Create an instance of the current context to return context information
        clientContext = SP.ClientContext.get_current();
        oList = clientContext.get_web().get_lists().getByTitle('list');
        var camlQuery = new SP.CamlQuery();
        camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name="Title"/><Value Type="Text">new item here</Value></Eq></Where></Query></View>');
        this.collListItem = oList.getItems(camlQuery);   
        clientContext.load(oList);
        clientContext.load(collListItem);
        clientContext.executeQueryAsync(onRequestSucceeded, onRequestFailed);
    }
    
    //the delegate of the method that is called when the request is executed successfully
    function onRequestSucceeded() 
    {
        var ary=new Array();
        var listItemEnumerator = collListItem.getEnumerator();
        while (listItemEnumerator.moveNext()) 
        {   
            count++;
            var oListItem = listItemEnumerator.get_current(); 
            message += '___'+'Title: ' + oListItem.get_item('Title');
            message += '___'+'ID: ' + oListItem.get_item('ID');
            ary.push(oListItem.get_item('ID'));
        }
        for(i in ary)
        {
            var item = oList.getItemById(ary[i]);
            item.set_item("Title", "new item here "+i);
    
            //Commits changed properties of the list item
            item.update();
        }
        clientContext.executeQueryAsync(onRequestSucceeded1, onRequestFailed1);
        
        $("#div1").text(message);   
    }
    
    //the delegate of the method that is called when the request is executed unsuccessfully
    function onRequestFailed(sender, args) 
    {
        alert('Error: ' + args.get_message());
    }
    
    function onRequestSucceeded1(sender, args) 
    {
        message+="---updated "+count+" items";
        
        $("#div1").text(message);
    }
    
    function onRequestFailed1(sender, args) 
    {
        alert('Error: ' + args.get_message());
    }
    
    </script>
    <input id="Button1" type="button" value="Run Code"/>
    <p/>
    <div id="div1">test</div>


    Reference:
    SP.ListItem.update() Method
    http://msdn.microsoft.com/en-us/library/office/ee659277(v=office.14).aspx

    Sample 7. 
    Create a custom list: Initialize a new instance of the SP.ListCreationInformation Class first, then set values that specifies the display name, list template of the new list, at last, use 
    the use SP.ListCollection.add(ListCreationInformation) to create the new list.

    <script type="text/javascript" src="/SiteAssets/jquery-1.10.2.min.js"></script>
    <script type="text/javascript">
    
    // When the body is loaded, the onload event handler executes each function whose name is contained in this array.
    _spBodyOnLoadFunctionNames.push("callCSOM");
    
    var clientContext;
    var oList;
    var message = "Web retrieved:";
    var count = 0;
    
    function callCSOM()
    {
        $("#Button1").click(function()
        {
            // Make sure the SharePoint script file 'sp.js' is loaded before your code runs.
            ExecuteOrDelayUntilScriptLoaded(sharePointReady, "sp.js");
        }); 
    }
    
    function sharePointReady() 
    {
        createList();
    }
    
    function createList() 
    {
        // Create an instance of the current context to return context information
        clientContext = SP.ClientContext.get_current();
        var oWebsite = clientContext.get_web();
        
        //Initializes a new instance of the SP.ListCreationInformation Class
        var listCreationInfo = new SP.ListCreationInformation();
    
        //Sets a value that specifies the display name of the new list
        listCreationInfo.set_title('My genericList List');
    
        //Sets a value that specifies the list server template of the new list
        listCreationInfo.set_templateType(SP.ListTemplateType.genericList);
    
        //Creates a new list or a document library
        this.oList = oWebsite.get_lists().add(listCreationInfo);
    
        clientContext.load(oList);
        clientContext.executeQueryAsync(
            Function.createDelegate(this, this.onQuerySucceeded), 
            Function.createDelegate(this, this.onQueryFailed)
        );
    }
    
    function onQuerySucceeded() 
    {
        var result = oList.get_title() + ' created.';
        alert(result);
    }
    
    function onQueryFailed(sender, args) {
        alert('Request failed. ' + args.get_message() + 
            '\n' + args.get_stackTrace());
    }
    </script>
    <input id="Button1" type="button" value="Run Code"/>
    <p/>
    <div id="div1">test</div>

    Reference:
    SP.ListCreationInformation() Constructor
    http://msdn.microsoft.com/en-us/library/office/ee659368(v=office.14).aspx
    SP.ListCreationInformation.title Property
    http://msdn.microsoft.com/en-us/library/office/ee551768(v=office.14).aspx
    SP.ListCreationInformation.templateType Property
    http://msdn.microsoft.com/en-us/library/office/ee547438(v=office.14).aspx
    SP.ListTemplateType Enumeration
    http://msdn.microsoft.com/en-us/library/office/ee549420%28v=office.14%29.aspx
    SP.ListCollection.add(parameters) Method
    http://msdn.microsoft.com/en-us/library/office/ee659708(v=office.14).aspx

    Sample 8. 
    We can call the deleteObject() function to delete a list named "My genericList List".

    function deleteList() 
    {
        var clientContext = SP.ClientContext.get_current();
        var oWebsite = clientContext.get_web();
        this.listTitle = 'My genericList List';
    
        this.oList = oWebsite.get_lists().getByTitle(listTitle);
        oList.deleteObject();
    
        clientContext.executeQueryAsync(
            Function.createDelegate(this, this.onQuerySucceeded), 
            Function.createDelegate(this, this.onQueryFailed)
        );
    }
    
    function onQuerySucceeded() {
        var result = listTitle + ' deleted.';
        alert(result);
    }
    
    function onQueryFailed(sender, args) {
        alert('Request failed. ' + args.get_message() + 
            '\n' + args.get_stackTrace());
    }


    Reference:
    ObjectContext.DeleteObject Method 
    http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.deleteobject%28v=vs.110%29.aspx

     

    Sample 9.
    Add a Text field into a list, set its maxlength as 100: Use the SP.FieldCollection.addFieldAsXml() to Creates a field based on the specified schema, Boolean value, and field options. Then cast a 
    specified client object to its derived type with the ClientContext.castTo(), then set the maxLength property of this field and commit the changed properties of the field.

    var clientContext;
    var oList;
    var message = "Web retrieved:";
    
    function addFieldToList() 
    {
        var clientContext = SP.ClientContext.get_current();
    
        var oList = clientContext.get_web().get_lists().getByTitle('list');
    
        //Creates a field based on the specified schema, Boolean value, and field options
        this.oField = oList.get_fields().addFieldAsXml(
            '<Field DisplayName=\'MyField_Text\' Type=\'Text\' />', 
            true, 
            SP.AddFieldOptions.defaultValue
        );
    
        //Casts a specified client object to its derived type
        var fieldText = clientContext.castTo(oField,SP.FieldText);
        fieldText.set_maxLength(100);
    
        //Commits changed properties of the field
        fieldText.update();
    
        clientContext.load(oField);
        clientContext.executeQueryAsync(
            Function.createDelegate(this, this.onQuerySucceeded), 
            Function.createDelegate(this, this.onQueryFailed)
        );
    }
    
    function onQuerySucceeded() {
        var result = oField.get_title() + ' added.';
        alert(result);
    }
    
    function onQueryFailed(sender, args) {
        alert('Request failed. ' + args.get_message() + 
            '\n' + args.get_stackTrace());
    }
    

    Reference:
    SP.FieldCollection.addFieldAsXml(schemaXml, addToDefaultView, options) Method
    http://msdn.microsoft.com/en-us/library/office/ee659655(v=office.14).aspx
    SP.ClientRuntimeContext.castTo(obj, type) Method
    http://msdn.microsoft.com/en-us/library/office/ee658922(v=office.14).aspx
    SP.FieldText.maxLength Property
    http://msdn.microsoft.com/en-us/library/office/ee548346(v=office.14).aspx
    SP.Field.update() Method
    http://msdn.microsoft.com/en-us/library/office/ee659278(v=office.14).aspx

    Sample 10. 
    Get all fields of a list.

    var fieldCollection;
    
    function getFields() 
    {
        var clientContext = SP.ClientContext.get_current();
        if (clientContext != undefined && clientContext != null) 
        {
            var webSite = clientContext.get_web();
            oList = webSite.get_lists().getByTitle("list");
            fieldCollection = oList.get_fields();
            clientContext.load(this.fieldCollection);
            clientContext.executeQueryAsync(Function.createDelegate(this, this.OnLoadSuccess), Function.createDelegate(this, this.OnLoadFailed));
        }
    }
    
    function OnLoadSuccess(sender, args) 
    {
        var fieldInfo = '';
        
        var fieldEnumerator = fieldCollection.getEnumerator();
        while (fieldEnumerator.moveNext()) 
        {   
            var field = fieldEnumerator.get_current(); 
            fieldInfo += '___'+'Title: ' + field.get_title();
            fieldInfo += '___'+'Description: ' + field.get_description();
        }
        $("#div1").text(fieldInfo);    
    }
    
    function OnLoadFailed(sender, args) 
    {
        alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    }

    Reference:
    SP.FieldCollection.getByInternalNameOrTitle(strName) Method
    http://msdn.microsoft.com/en-us/library/office/ee658548(v=office.14).aspx

    Sample 12. 
    Delete a field in a list.

    var fieldCollection;
    var oneField = null;
    
    function deleteField() 
    {
        var clientContext = SP.ClientContext.get_current();
        if (clientContext != undefined && clientContext != null) 
        {
            var webSite = clientContext.get_web();
            oList = webSite.get_lists().getByTitle("list");
            fieldCollection = oList.get_fields();
            this.oneField = fieldCollection.getByInternalNameOrTitle("A");
            this.oneField.deleteObject();
    
            clientContext.executeQueryAsync(Function.createDelegate(this, this.OnLoadSuccess), Function.createDelegate(this, this.OnLoadFailed));
        }
    }
    
    function OnLoadSuccess(sender, args) 
    {
        alert("Deleted a field");    
    }
    
    function OnLoadFailed(sender, args) 
    {
        alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    }


    Sample 13.
    Add user custom action to the Edit Control Block of a list item: At first, get the collection of all user custom actions for the list with List.get_userCustomActions(), add a new SP.UserCustomAction Class custom action to the collection, then set the location, sequence, title, URL property of the custom action and commit the changed properties.

    function createUserCustomActionECB() {
    
        var clientContext = SP.ClientContext.get_current();
        var oWebsite = clientContext.get_web();
        this.oList = oWebsite.get_lists().getByTitle('list');
    
        //Gets a value that specifies the collection of all user custom actions for the list
        var collUserCustomAction = oList.get_userCustomActions();
            
        //Adds a new SP.UserCustomAction Class custom action to the collection    
        var oUserCustomAction = collUserCustomAction.add();
    
        //sets the location or other properties of the custom action
        oUserCustomAction.set_location('EditControlBlock');
    
        //sets the value that specifies an implementation-specific value that determines the order of the custom action that appears on the page. 
        //Its value must be equal to or greater than 0. Its value must be equal to or less than 65536
        oUserCustomAction.set_sequence(100);
        oUserCustomAction.set_title('My First User Custom Action');
    
        //sets the URL, URI, or ECMAScript (JScript, JavaScript) function associated with the action
        oUserCustomAction.set_url('http://www.bing.com');
        oUserCustomAction.update();        
        clientContext.load(oList, 'Title' ,'UserCustomActions');    
        clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
    }
    
    function onQuerySucceeded() {
    
        alert('Custom action created for ' + this.oList.get_title());
    }
    
    function onQueryFailed(sender, args) {
    
        alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    }


    Reference:
    SP.List.userCustomActions Property
    http://msdn.microsoft.com/en-us/library/office/ee547424(v=office.14).aspx
    SP.UserCustomActionCollection.add() Method
    http://msdn.microsoft.com/en-us/library/office/ee659103(v=office.14).aspx
    SP.UserCustomAction.location Property
    http://msdn.microsoft.com/en-us/library/office/ee553783(v=office.14).aspx
    SP.UserCustomAction.sequence property
    http://msdn.microsoft.com/en-us/library/office/jj246287.aspx
    SP.UserCustomAction.url property
    http://msdn.microsoft.com/en-us/library/office/jj246629.aspx
    Default Custom Action Locations and IDs
    http://msdn.microsoft.com/en-us/library/bb802730.aspx


    Sample 14.
    Add user custom action to the Edit Control Block of the site actions: Similar to the process of adding to the Edit Control Block of a list item, we need to set a value 
    that specifies an implementation-specific value that determines the position of the custom action in the page.

    function createUserCustomActionSite() {
    
        var clientContext = SP.ClientContext.get_current();
        this.oWebsite = clientContext.get_web();
        var collUserCustomAction = oWebsite.get_userCustomActions();
            
        var oUserCustomAction = collUserCustomAction.add();
        oUserCustomAction.set_location('Microsoft.SharePoint.StandardMenu');
    
        //sets a value that specifies an implementation-specific value that determines the position of the custom action in the page
        oUserCustomAction.set_group('SiteActions');
        oUserCustomAction.set_sequence(101);
        oUserCustomAction.set_title('Website User Custom Action');
        oUserCustomAction.set_description('This description appears on the Site Actions menu.');
        oUserCustomAction.set_url('http://www.bing.com');
        oUserCustomAction.update();
            
        clientContext.load(oWebsite, 'Title', 'UserCustomActions');
        
        clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
    }
    
    function onQuerySucceeded(sender, args) {
    
        alert('Custom action created for ' + this.oWebsite.get_title());
    }
    
    function onQueryFailed(sender, args) {
    
        alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    }

    Reference:
    Default Custom Action Locations and IDs
    http://msdn.microsoft.com/en-us/library/bb802730.aspx

    Sample 15.
    Modify the properties of user custom action.

    var collUserCustomAction;
    
    function modifyUserCustomAction() {
    
        this.clientContext = SP.ClientContext.get_current();
        var oWebsite = clientContext.get_web();
        this.oList = oWebsite.get_lists().getByTitle('List19_jsomtest');
        this.collUserCustomAction = oList.get_userCustomActions();        
        clientContext.load(oList,'UserCustomActions','Title');
        clientContext.load(collUserCustomAction);
        clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
    }
    
    function onQuerySucceeded() {
    
        var customActionEnumerator = collUserCustomAction.getEnumerator();
        while (customActionEnumerator.moveNext()) 
        {
            var oUserCustomAction = customActionEnumerator.get_current();
            if (oUserCustomAction.get_title() == 'My First User Custom Action') 
            {
                oUserCustomAction.set_url('http://www.bing.com');
                oUserCustomAction.update();    
                clientContext.load(oUserCustomAction);
                clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded1), Function.createDelegate(this, this.onQueryFailed));
            }
        }
    }
    
    function onQuerySucceeded1() {
    
        alert('Custom action changed for ' + this.oList.get_title());
    }
    
    function onQueryFailed(sender, args) {
    
        alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    }


    Sample 16.

    Delete user custom action of list item by name.

    var clientContext;
    var oWebsite;
    var oList;
    var collUserCustomAction;
    
    function deleteUserCustomAction() {
    
        this.clientContext = SP.ClientContext.get_current();
        this.oWebsite = clientContext.get_web();
        this.oList = oWebsite.get_lists().getByTitle('List19_jsomtest');
        this.collUserCustomAction = oList.get_userCustomActions();        
        clientContext.load(oList,'UserCustomActions','Title');
        clientContext.load(collUserCustomAction);
        clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
    }
    
    function onQuerySucceeded() {
    
        var customActionEnumerator = collUserCustomAction.getEnumerator();
        while (customActionEnumerator.moveNext()) 
        {
            var oUserCustomAction = customActionEnumerator.get_current();
            if (oUserCustomAction.get_title() == 'My First User Custom Action') 
            {
                oUserCustomAction.deleteObject();
                oList.update();    
                clientContext.load(oList);
                clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded1), Function.createDelegate(this, this.onQueryFailed));
                break;
            }
        }
    }
    
    function onQuerySucceeded1() {
    
        alert('Custom action deleted for ' + this.oList.get_title());
    }
    
    function onQueryFailed(sender, args) {
    
        alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    }

    Sample 17.

    Retrieve id, title properties of all the groups in this site.

    function retrieveAllGroups() {
    
        var clientContext = new SP.ClientContext.get_current();
        this.collGroup = clientContext.get_web().get_siteGroups();
        clientContext.load(collGroup);
        clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
    }
    
    function onQuerySucceeded() {
    
        var groupInfo = "";
    
        var groupEnumerator = collGroup.getEnumerator();
        while (groupEnumerator.moveNext()) {
            var oGroup = groupEnumerator.get_current();
            groupInfo += "\nGroup ID:" + oGroup.get_id() + " ----Group Title:" + oGroup.get_title();
        }
        alert(groupInfo);
    }
    
    function onQueryFailed(sender, args) {
        alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    }

    Reference:
    SP.Group Properties
    http://msdn.microsoft.com/en-us/library/office/ee557729(v=office.14).aspx

    Sample 18.
    Add users to a SharePoint Group: At first, get the specific group by id, then initialize a instance of UserCreationInformation, set the email, loginName, title properties of this user. At last, use the 
    UserCollection.add(UserCreationInformation) function to create an user with these properties.

    function addUserToSharePointGroup() {
    
        var clientContext = new SP.ClientContext.get_current();
        var collGroup = clientContext.get_web().get_siteGroups();
        var oGroup = collGroup.getById(GroupID);
        var userCreationInfo = new SP.UserCreationInformation();
        userCreationInfo.set_email('alias@somewhere.com');
        userCreationInfo.set_loginName('DOMAIN\alias');
        userCreationInfo.set_title('User');
        this.oUser = oGroup.get_users().add(userCreationInfo);
    
        clientContext.load(oUser);
        clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
    
    }
    
    function onQuerySucceeded() {
    
        alert(this.oUser.get_title() + " added.");
    }
    
    function onQueryFailed(sender, args) {
    
        alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    }
    Reference:
    SP.UserCreationInformation Properties
    http://msdn.microsoft.com/en-us/library/office/ee549307(v=office.14).aspx


    Please click to vote if the post helps you. This can be beneficial to other community members reading the thread.


    • Edited by ForumFAQ Thursday, January 16, 2014 9:13 AM
    Thursday, January 16, 2014 8:02 AM