Provisioning a List on the Host Web from the App Web with JavaScript Object Model (JSOM)

Below is some sample code of how to provision a list from the app web via SharePoint JavaScript object model

   1: function CreateList(title, url, templateType, hidden) {

   2:  

   3:     //Using the App Web as the client context

   4:     clientContext = new SP.ClientContext.get_current();

   5:  

   6:     //Get the host web URL from the query string params

   7:     //I have a function getHostWebUrl() - which is not included.

   8:     // Some Ideas Here: http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript

   9:     var hostWebUrl = getHostWebUrl();

  10:     //Using the hostWebContext as an AppContextSite

  11:     hostWebContext = new SP.AppContextSite(clientContext, hostWebUrl);

  12:  

  13:     //Create List Code

  14:     var listCreation = new SP.ListCreationInformation();

  15:     listCreation.set_title(title);

  16:     listCreation.set_templateType(templateType);

  17:     listCreation.set_url(url);

  18:  

  19:     //must use the hostWebContext to get the list in that site

  20:     var lists = hostWebContext.get_web().get_lists();

  21:     var list = lists.add(listCreation);

  22:     list.set_hidden(hidden);

  23:     list.set_onQuickLaunch(false);

  24:     list.update();

  25:  

  26:     //Always use the context of the app web to do the work or load and executing

  27:     clientContext.load(list);

  28:     clientContext.executeQueryAsync(function() {

  29:         console.log("Created List : \"" + title + "\"");

  30:     }, function(sender, args) {

  31:         console.log("Failed to create list : " + title);

  32:         console.log("<span style='color:red'>Reason : " + args.get_message() + "</span>");

  33:     });

  34:  

  35: }

  36:  

  37: // parameters : List Name, List Url, Template Type (can be ListTemplateType or Template ID, Hidden)

  38: CreateList("My Test List", "Lists/MyTestList", SP.ListTemplateType.genericList, false);

  39: CreateList("My Test List", "Lists/MyTestList", 171, false);

Advertisements