Showing posts with label SharePoint 2013. Show all posts
Showing posts with label SharePoint 2013. Show all posts

Tuesday 28 June 2016

Create, Retrieve, Update Or Delete Sub Sites On SharePoint Using JavaScript Object Model

In this post, you will learn how to retrieve, create, update or delete the sites under a site collection, using JavaScript Object Model (JSOM) on SharePoint 2013 / SharePoint Online sites like O365. The sites are considered as the sub sites within the site collection.

Before executing any operation, load the required scripts like SP.js, SP.RunTime.js. If the scripts are not initialized, use the snippet, given below:
  1. var scriptbaseURL = _spPageContextInfo.webServerRelativeUrl + "_layouts/15/";    
  2. $.getScript(scriptbaseURL + "SP.Runtime.js",    
  3.     function ()  
  4.    {    
  5.         $.getScript(scriptbaseURL + "SP.js", RequiredFunctions);    
  6.     }    
  7. );   


Create Sub Site:

The operation will create a sub site within the site collection. 
  • Access the context of the site and the Web object, using root site URL or the current context.
  • Create WebCreationInformation Object. Set the necessary parameters like title, description, URL, Web template, site permission and the language.
  • Add it to the existing Web collections and update the current site. Execute the request.
The code snippet, given below, helps in creating a site.
  1. var rootSiteUrl = "https://abc.sharepoint.com";  
  2. var ctx = new SP.ClientContext(rootSiteUrl);  
  3. var web = ctx.get_web();  
  4. var webInfo = new SP.WebCreationInformation();  
  5. webInfo.set_title('subsite');  
  6. webInfo.set_description('subsite description');  
  7. webInfo.set_url('subsite');  
  8. webInfo.set_webTemplate('STS#0');  
  9. webInfo.set_useSamePermissionsAsParentSite(true);  
  10. webInfo.set_language(1033);  
  11.   
  12. web.get_webs().add(webInfo);  
  13. web.update();  
  14. ctx.executeQueryAsync(function(){  
  15.     console.log("Sub Site Created");  
  16. },  
  17. function(sender, args){  
  18.     console.log("Failed to create sub site : " + args.get_message());  
  19. }  
  20. );   


Retrieve Sub Site:

The site properties can be retrieved, using JSOM. 
  • Access the context and the Web object, using sub site URL.
  • The basic properties can be retrieved from the above Web object.
  • Other properties and information can be retrieved by accessing the necessary properties and methods. For example, just loading the Web object will not be able to retrieve more information on the features. To get the active features on the site, we need to access the feature on the select and load the object to retrieve the features information. Similarly, other collection values needs to be retrieved by explicitly accessing the methods. 
The code snippet, given below, helps to retrieve the site properties.
  1. var subSiteUrl = "https://abc.sharepoint.com/subsite";  
  2. var ctx = new SP.ClientContext(subSiteUrl);  
  3. var web = ctx.get_web();  
  4. var features = web.get_features();  
  5. // Similarly other properties and information can be retrieved from the site  
  6. ctx.load(web);  
  7. ctx.load(features);  
  8. ctx.executeQueryAsync(function(){  
  9.     console.log("Title : " + web.get_title());  
  10.     console.log("Description : " + web.get_description());  
  11.     console.log("Totally " + features.get_count() + " Features active on the site")  
  12.     // Similarly other feature properties can be retrieved.  
  13. },  
  14. function(sender, args){  
  15.     console.log("Failed to retrieve sub site info : " + args.get_message());  
  16. }  
  17. );   


Update Sub Site:

The update operation will be very similar to create an operation. 
  • Access the context of the site and the Web object, using sub site URL.
  • Update the necessary properties, using the set methods.
  • Update and execute the request. 
The code snippet, given below, helps in updating the site properties. Here, title and the description of the sub site are updated.
  1. var subSiteUrl = "https://abc.sharepoint.com/subsite";  
  2. var ctx = new SP.ClientContext(subSiteUrl);  
  3. var web = ctx.get_web();      
  4. web.set_title('new subsite');   
  5. web.set_description('subsite description updated');  
  6. web.update();  
  7. ctx.executeQueryAsync(function(){  
  8.     console.log("Sub site properties updated");  
  9.     console.log("Title : " + web.get_title());  
  10.     console.log("Description : " + web.get_description());  
  11.  },  
  12.  function(sender, args){  
  13.     console.log("Failed to create sub site : " + args.get_message());  
  14.  }  
  15. );   


Delete Sub Site:

The delete operation will be very similar to create or update operations. Here, no input data is required. 
  • Access the context of the site and the Web object, using sub site URL.
  • Using the Web object, delete the site with delete object method.
  • Execute the request, using the client context. 
The code snippet, given below, helps to delete the site.
  1. var subSiteUrl = "https://abc.sharepoint.com/subsite";  
  2. var ctx = new SP.ClientContext(subSiteUrl);  
  3. var web = ctx.get_web();      
  4. web.deleteObject();  
  5. ctx.executeQueryAsync(function(){  
  6.     console.log("Sub site deleted");          
  7. },  
  8. function(sender, args){  
  9.     console.log("Failed to create sub site : " + args.get_message());  
  10. }  
  11. );  

Note: In these cases, you can check the result values in a Browser debugger console. You can change the logic to display the results on the pages. Place these scripts on the page, using the Web parts (Content Editor / Script Editor / any custom Web part) at the site collection level.  

Create, Retrieve, Update or Delete Sub Sites On SharePoint Using REST API

In this post, you will learn how to retrieve, create, update or delete the sites under a site collection, using REST API's on SharePoint 2013 / SharePoint 2016 / SharePoint Online sites like O365. The sites are considered as sub sites within the site collection.


Steps Involved:
  • Identify the site URL and build the REST API URL.
  • Use AJAX jQuery call to accomplish the necessary operation.
  • You can set the return value type in the AJAX call request. In my case, I have specified JSON to be the return value in the data parameter.
  • In these cases, you can check the result values in a Browser debugger console. You can change the logic to display the results on the pages.
  • Place these scripts on the page, using the Web parts (Content Editor / Script Editor / any custom Web part) at the site collection level.


Create Sub Site:

The operation will create a sub site within the site collection. 
  • The REST API will complete the create operation http://siteurl/_api/contextinfo.
  • The method or type should be POST. 
  • The form digest value is required to validate the create operation. Hence, before creating the request, the form digest value should be retrieved. We can use an AJAX call to accomplish all the tasks. The REST API will retrieve form digest value  http://siteurl/_api/contextinfo. Or simply from the request digest control, we can retrieve the form digest.value.$('#__REQUESTDIGEST').val().
  • For creating a site, we need to send the necessary information to the Service. For this, we will use JSON format, where we will send site title, site template, site URL, description, unique permissions etc.
  • In the header, send the required content type and form digest value for the security validation.
To get the form digest value, you can use the logic, given below:
  1. $.ajax  
  2.     ({    
  3.         url: "/_api/contextinfo",    
  4.         type: "POST",    
  5.         async: false,    
  6.         headers: { "accept""application/json;odata=verbose" },    
  7.         success: function(data){    
  8.              requestDigest = data.d.GetContextWebInformation.FormDigestValue;  
  9.         },    
  10.         error: function(data){    
  11.         }    
  12.     });  
The code snippet given below helps in creating a site. In this example, the form digest value is retrieved directly from the page control. (The operation given above is not required)
  1. var restAPIURL = "/_api/web/webinfos/add";  
  2. var newSiteData = JSON.stringify(
  3. {
  4.     'parameters': {  
  5.          '__metadata': {   
  6.                'type''SP.WebInfoCreationInformation'   
  7.          },  
  8.          'Url''SubSite',   
  9.          'Description''Subsite created from REST API',  
  10.          'Title''SubSite',  
  11.          'Language': 1033,  
  12.          'WebTemplate''STS#0',  
  13.           'UseUniquePermissions'false  
  14.     }  
  15.  });  
  16. $.ajax  
  17. ({    
  18.     url: restAPIURL,    
  19.     type: "POST",    
  20.     async: false,  
  21.     data: newSiteData,    
  22.     headers: {  
  23.         "accept""application/json;odata=verbose",  
  24.         "content-type""application/json;odata=verbose",  
  25.         "X-RequestDigest": $('#__REQUESTDIGEST').val()  
  26.     },   
  27.     success: function(data){    
  28.          console.log('site created');  
  29.     },    
  30.     error: function(data){   
  31.         console.log('Error creating site');   
  32.     }    
  33. });   


Retrieve Sub Site:

The site properties can be retrieved, using REST API. The URL to access the properties is,http://subsiteurl/_api/web

This will get the basic properties of the site. To get more properties, we need to use select and expand parameters in the URL. For example, the URL given above will not fetch more information on the features. To get the active features on the site, we need to pass the feature on the select and expand parameters to retrieve the information. Similarly, other collection values needs to be retrieved with the select and expand parameters.

The code snippet given below helps to retrieve the site properties.
  1. //var restAPIURL = "/subsite/_api/web?$select=Features&$expand=Features/Id"  
  2. var restAPIURL = "/subsite/_api/web"  
  3. $.ajax  
  4. ({    
  5.     url: restAPIURL,    
  6.     type: "GET",  
  7.     headers: { "accept""application/json;odata=verbose" },  
  8.     success: function(data){    
  9.          console.log("Title : " + data.d.Title);  
  10.          console.log("Description : " + data.d.Description);  
  11.     },    
  12.     error: function(data){   
  13.         console.log('Error getting info');   
  14.     }    
  15. });  


Update Sub Site

The update operation will be very similar to creating an operation.
  • The URL for updating the operation will be, http://subsiteurl/_api/web.
  • The method or type will be POST.
  • The properties that need to be updated are sent, using JSON string.
  • In the header parameter, we need to set and send the content type for the data type, form digest value for the security validation and “Merge” method for the update operation.
The code snippet given below helps in updating the site properties. Here, just update the title of the sub site created in the above sections:
  1. var updateSiteData = JSON.stringify(
  2. {  
  3.     '__metadata': {   
  4.          'type''SP.Web'   
  5.     },  
  6.     'Description''Subsite updated from REST API',  
  7.     'Title''New SubSite',  
  8.  });  
  9.   
  10. restAPIURL = "/subsite/_api/web"  
  11. $.ajax  
  12. ({    
  13.     url: restAPIURL,    
  14.     type: "POST",  
  15.     async: false,  
  16.     data: updateSiteData,  
  17.     headers: {  
  18.          "accept""application/json;odata=verbose",  
  19.         "content-type""application/json;odata=verbose",  
  20.         "X-RequestDigest": $('#__REQUESTDIGEST').val(),    
  21.         "X-HTTP-Method""MERGE"  
  22.     },   
  23.     success: function(data){    
  24.          console.log('site updated');  
  25.     },    
  26.     error: function(data){   
  27.         console.log('Error updating site');   
  28.     }    
  29. });  


Delete Sub Site:

The delete operation will be very similar to create or update operations. Here, no input data is required.
  • The URL will be http://subsiteurl/_api/web.
  • The type or method will be POST.
  • In the header parameter, we need to set and send the content type for data type, form digest value for the security validation and “Delete” method for the delete operation.
The code snippet given below helps delete the site.
  1. var restAPIURL = "/subsite/_api/web"  
  2. $.ajax  
  3. ({    
  4.     url: restAPIURL,    
  5.     type: "POST",  
  6.     async: false,  
  7.     headers: {  
  8.          "accept""application/json;odata=verbose",  
  9.         "content-type""application/json;odata=verbose",  
  10.         "X-RequestDigest": $('#__REQUESTDIGEST').val(),    
  11.         "X-HTTP-Method""DELETE"  
  12.     },   
  13.     success: function(data){    
  14.          console.log('site deleted');  
  15.     },    
  16.     error: function(data){   
  17.         console.log('Error deleting site');   
  18.     }    
  19. });