cancel
Showing results for 
Search instead for 
Did you mean: 
Not applicable

Nintex Forms O365 - Getting SharePoint ClientContext Do's and Dont's

Nintex Forms for Office 365 is developed following the SharePoint App Model which lets you run your application outside of SharePoint from any web server and it allows developers to interact with SharePoint resources using JSOM on the client side.

To work with SharePoint JSOM we need to get hold of the ClientContext which exposes useful APIs to us. There are many tutorials on the web showing how to do that. A good starting point is referenced on msdn

Basically all you need to do is reference to relevant SharePoint script files and initialize the ClientContext with the site url that you want to query. However, be aware of the following:

Do's:

  • Wrap your codes within the Nintex client ready events
    NWF.FormFiller.Events.RegisterAfterReady(function (){});    
  • Only load the SharePoint scripts that you need
  • Load SharePoint scripts asynchronously
  • Leverage the built-in Nintex cachedScript function which return a promise to cache your scripts NWF$.cachedScript('myscripturl');
  • Be aware of cross domain restrictions. Use the cross-domain library if you want to interact with the Host Web for example

Dont's:

Nintex Forms for Office 365 by default loads most of the core SharePoint scripts, therefore if you load a script that was already loaded you might ended with an error on your developer console and an unresponsive form probably; in that case check the console error and remove the duplicated script. For example, the form will load, but not only, these core files by default:

  • 'SP.Runtime.js'
  • 'SP.RequestExecutor.js'
  • 'SP.js'

The code snippet below shows how you can load SharePoint scripts and initialize a ClientContext.

// A sample how you can load your SharePoint scripts and initialize a clientContext.

NWF.FormFiller.Events.RegisterAfterReady(function (){    

  /*if you need to load scripts other than those pre-loaded by Nintex Forms*/

  //loadScripts().done(function(){

  // getDataFromSharePoint();

  //});

  /* if you don't need to load any specific scripts and use those pre-loaded by Nintex Forms*/

  // getDataFromSharePoint();

});

function loadScripts(){

  var def = NWF$.Deferred();

  var layoutsPath = '/_layouts/15/';

  var appWebUrl = NF.Url.getQueryStringParameter("SPAppWebUrl");

  var hostUrl = NF.Url.getQueryStringParameter("SPHostUrl");

  var scriptsPath = hostUrl + layoutsPath;

  (function () {

  // only load the scripts that you need

  return NWF$.cachedScript(scriptsPath + 'mysharepointneeded.js');

  })()

  .pipe(function () {

  // you can chain, and load many script by using pipe callback

  return NWF$.cachedScript(scriptsPath + 'mysharepointneeded.js');

  })

  .done(function () {

  def.resolve();

  })

  return def.promise();

}

function getDataFromSharePoint() {

    var clientContext;

    var factory;

   

  clientContext = new SP.ClientContext(appwebUrl);

  factory = new SP.ProxyWebRequestExecutorFactory(appwebUrl);

    clientContext.set_webRequestExecutorFactory(factory);

   

  // write your codes here to query SharePoint

}

NB: Above code snippet is for reference purposes only

Labels: (1)
Reply
12 Replies
stuart_holding
Nintex Newbie

Re: Nintex Forms O365 - Getting SharePoint ClientContext Do's and Dont's

Hi Cellou,

I'm trying to use your examples above to setup REST query back to the source item and read some properties from within the Nintex Form.

I have the following code added to the from, but I am getting a null reference on anything underneath the SP. namespace. In the below, when I try to initiate the clientContext variable, I get an "SP is not defined" error.

According to the above, SP.js, SP.Runtime.js etc etc should all be loaded yeah?

NWF.FormFiller.Events.RegisterAfterReady(function () {

  debug(NWF$(".fp-RelatedItems").text());

  var appwebUrl = decodeURIComponent(getParameterByName("SPAppWebUrl"));

    var listID = getParameterByName("List");

  var itemID = getParameterByName("ID");

  var hostUrl = getParameterByName("SPHostUrl");

  debug("listID : " + listID + " itemID : " + itemID + " hostUrl : '" + hostUrl + "'");

  var clientContext = new SP.ClientContext(appwebUrl); 

  var factory = new SP.ProxyWebRequestExecutorFactory(appwebUrl);

    clientContext.set_webRequestExecutorFactory(factory);

  var url = appwebUrl + "/_api/SP.AppContextSite(@target)/web/lists(" + listID + ")/items(" + itemID + ")?@target='" + hostUrl + "'";

    clientContext.executeAsync({

        url: url,

        method: "GET",

        headers: { "Accept": "application/json; odata=verbose" },

        success: successTitleHandlerXD,

        error: errorTitleHandlerXD

    });

  //Success Title

  function successTitleHandlerXD(data) {

  var jsonObject = JSON.parse(data.body);

  debug("<b>Via Cross Domain the title is:</b> " + jsonObject.d.Title);

  debug("<b>Via Cross Domain the RelatedItems is:</b> " + jsonObject.d.RelatedItems);

  }

  //Error with Title.

  function errorTitleHandlerXD(data, errorCode, errorMessage) {

  debug("Could not complete cross-domain call: " + errorMessage);

  }

  function debug(message)

  {

  if (typeof (console) !== "undefined")

  console.log("RelatedItems: " + message);

  }

  function getParameterByName(name) {

  name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");

  var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),

  results = regex.exec(location.search);

  return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));

  }

});

0 Kudos
Reply
Not applicable

Re: Nintex Forms O365 - Getting SharePoint ClientContext Do's and Dont's

Hi Stu,

What is happening is that your script execute before the SP scripts have finished loading. the above snippet is suitable for scenarios where you need to query SharePoint based on a user input in which case the default SP scripts have finished loading.

However if you need to execute a query to SharePoint while the form is loading you could do something like this...

NWF.FormFiller.Events.RegisterAfterReady(function () {

  try

  {

  loadScripts().done(function(){

 

   var appwebUrl = decodeURIComponent(getParameterByName("SPAppWebUrl"));

  var listID = getParameterByName("List");

   var itemID = getParameterByName("ID");

   var hostUrl = getParameterByName("SPHostUrl");

 

   var clientContext = new SP.ClientContext(appwebUrl);

 

 

  });

  }

  catch(e)

  {

  }

});

However note that you might get some error on the console when doing this, but you should be able to get the clientContext.


We will look into exposing more events that will notify when the SP scripts have finished loading. I will update this post when we do, but i cannot provide any timeline on when that will happen.

Thank you

Reply
patrickabel
Nintex Newbie

Re: Nintex Forms O365 - Getting SharePoint ClientContext Do's and Dont's

I have recently upgraded to the latest version of Nintex Forms for Office 365 (1.2.3.0). In doing so, I am now encountering a 403 access denied error when performing REST calls to update SharePoint lists within my form.

Is anyone else experiencing this issue with the latest update?

I was able to bypass the 403 error by forcing SP.RequestExecutor.js to be loaded (contradictory to the above), but in doing so have introduced an issue where form controls (lookups) don't load on the form (stuck "Loading...").

I believe I can state with certainty that this error I'm seeing spawns from the 1.2.3.0 update. Before fully upgrading, I had the same Nintex Form and embedded code running on two different tenants. The tenant with the latest update was failing whereas the previous version was working.

Perhaps the DEV pattern for Client Context has changed with the latest updates?

0 Kudos
Reply
ksivanandan
Nintex Newbie

Re: Nintex Forms O365 - Getting SharePoint ClientContext Do's and Dont's

Hi Patrick

Was this ever resolved, I am on the same boat.

NWF$(document).ready(function() {

       NWF$.getScript(SPHostUrl + "/_Layouts/15/SP.RequestExecutor.js", function (data) {
                 window.setTimeout(function (){
                           ready = true;
                           NWF$("#" + Unit).bind("change", GetApprovers);
                           NWF$("#"+ NounModifier).bind("change", GetCharacteristics);
                           GetApprovers();
                           GetMROTeam();

                    }, 500);
         });

});

The GetApprovers() and GetMROTeam() both have REST API queries

var restQuery = SPAppWebUrl + "/_api/SP.AppContextSite(@target)/web/lists/GetByTitle('MRORequestFormApprovals')/items?$select=Unit,Approver/Name,Approver/Id,Approver/FirstName,Approver/LastName,Approver/Title,ApproverTitle,DefaultApprover&$expand=Approver&$filter=(Unit eq '" + selectedUnit + "')&@target='" + SPHostUrl + "'";

var restQuery = SPAppWebUrl + "/_api/SP.AppContextSite(@target)/web/lists/GetByTitle('MRORequestFormApprovals')/items?$select=Unit,Approver/Name,Approver/Id,Approver/FirstName,Approver/Title,Approver/LastName,ApproverTitle&$expand=Approver&$filter=(ApproverTitle eq 'MRO Team')&@target='" + SPHostUrl + "'";

But this causes the loading issues - if I remove the NWF$.getScript(SPHostUrl + "/_Layouts/15/SP.RequestExecutor.js", function (data) - then I get the error 

SP.RequestExecutor.js:2 Uncaught TypeError: Cannot convert undefined or null to object at SP.RequestExecutor.js:2

Thanks for any help

Kalpana

0 Kudos
Reply
patrickabel
Nintex Newbie

Re: Nintex Forms O365 - Getting SharePoint ClientContext Do's and Dont's

‌ this was never resolved for me. I've had an open Nintex support ticket on it for 9 months now but I think this is a little too "custom" to be pursued further by their dev team.

0 Kudos
Reply
ksivanandan
Nintex Newbie

Re: Nintex Forms O365 - Getting SharePoint ClientContext Do's and Dont's

Thanks for your prompt response - how did you resolve this issue?

0 Kudos
Reply
patrickabel
Nintex Newbie

Re: Nintex Forms O365 - Getting SharePoint ClientContext Do's and Dont's

I was unable to solve the issue given the functionality I was using previously is no longer possible.

I simply abandoned client-side POST calls within Nintex forms (updating items, creating items, etc).

0 Kudos
Reply
ksivanandan
Nintex Newbie

Re: Nintex Forms O365 - Getting SharePoint ClientContext Do's and Dont's

That is a shame. 

Did this not work?  

0 Kudos
Reply
Highlighted
patrickabel
Nintex Newbie

Re: Nintex Forms O365 - Getting SharePoint ClientContext Do's and Dont's

Hello Kalpana Sivanandan‌,

The logic mentioned in the above URL works because it is retrieving data (i.e. method = GET) from a SharePoint list via REST. It's only in attempting to create or modify SharePoint list items via a POST call that you'll experience the 403 error.

It's unfortunate that this is no longer possible, but to be honest this type of client-side logic belongs in a SPA, not within a Nintex Form anyway.

0 Kudos
Reply