Skip to main content
Nintex Community Menu Bar

Sharing two pieces of JavaScript getting List Item(s) and User Profiles from Nintex Forms for Office 365. The two JavaScript was tested based on Nintex Forms for Office 365, App Version: NFO 1.2.3.0. Please take note that this code is tested only based on the above mentioned version of Nintex Forms, it might not be optimized in term of performance or simplicity.

 

 

Calling Sharepoint Online REST API to query host web's custom list from within Nintex Forms for Office 365 (i.e. App web).

var pollSP;  
NWF.FormFiller.Events.RegisterAfterReady(function (){ 
    pollSP = setInterval(checkSPLoad, 500); 
}); 
     
function checkSPLoad(){ 
    if (clientContext){ 
        window.clearInterval(pollSP); 
          var hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
          var appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl")); 
          var layoutsPath = "/_layouts/15/"; 
          var scriptbase = appweburl + layoutsPath; 
 
          NWF$.getScript(scriptbase + "SP.js",
               function () {
                              NWF$.getScript(scriptbase+ "SP.RequestExecutor.js", execCrossDomainRequest);
               }
          );
    } 
 
     function execCrossDomainRequest(){
          var deferred = NWF$.Deferred();
          var url = appweburl + "/_api/SP.AppContextSite(@target)/web/lists/GetByTitle('MyExpense')/Items?$select=ID,Title&@target='" + hostweburl + "'";
          var executor = new SP.RequestExecutor(appweburl);
          executor.executeAsync(
               {
                    url: url,
                    method: "GET",
                    headers: {"accept": "application/json;odata=verbose"},
                    success: function (data) {
                         var jsonobj = JSON.parse(data.body);
                         var results = jsonobj.d.results;
                         deferred.resolve(data);
                         var msg = "";
                         for (var i = 0; i < results.length; i++){
                              msg = msg + resultsji].Title + ";";
                         }
                         alert(msg);
                    },
                    error: function (data) {
                         deferred.reject(data);
                         alert("data");
                    }
               }
          );
     }
}‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

 

Querying current user's profile from Nintex Forms for Office 365. 

NWF.FormFiller.Events.RegisterAfterReady(function (){  
     var clientContext;
     var hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
     var appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl")); 
     var layoutsPath = "/_layouts/15/"; 
     var scriptbase = appweburl + layoutsPath; 
 
     NWF$.getScript(scriptbase + "SP.js").then(function(){
          return NWF$.getScript(scriptbase + "SP.RequestExecutor.js");
     }).then(function(){
          return NWF$.getScript(scriptbase + "init.js");
     }).then(function(){
          return NWF$.getScript(scriptbase + "SP.UserProfiles.js");
     }).then(execCrossDomainRequest);
 
     function execCrossDomainRequest(){
          var deferred = NWF$.Deferred();
          
          var con = SP.ClientContext.get_current();
          clientContext = new SP.ClientContext(appweburl);
          var factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
          clientContext.set_webRequestExecutorFactory(factory);
          
          var hostWeb = new SP.AppContextSite(clientContext, hostweburl).get_web();
          var appWeb = new SP.AppContextSite(clientContext, appweburl).get_web();
          
          var url = appweburl + "/_api/SP.UserProfiles.PeopleManager/GetMyProperties";
     
          var requestHeaders = {
               "Accept": "application/json;odata=verbose"
          };
           
          var executor = new SP.RequestExecutor(appweburl);
          executor.executeAsync(
               {
                    url: url,
                    contentType: "application/json;odata=verbose",
                    method: "GET",
                    headers: requestHeaders,
                    success: function (data) {
                         var msg = "";
                         var parsedData = JSON.parse(data.body);
                         var properties = parsedData.d.UserProfileProperties.results;
                         for (var i = 0; i < properties.length; i++){
                              var property = propertiesli];
                              msg = msg + property.Key + ":" + property.Value + ",";
                         }
                         deferred.resolve(parsedData);
                         alert(msg);
                    },
                    error: function (data) {
                         deferred.reject(data);
                         alert("failed");
                    }
               }
          );
     }

});‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

Really useful stuff.

Could I suggest comments in the code to help users understand what functions are doing what so they can adapt it as required more easily. You may also want to illustrate how you'd integrate this into the form as well.

Just to help complete the picture for people who might be fairly new to this.


hi Ryan,

Thanks for the comments, will take note of that for my next write-up. I was making assumptions of certain level of javascript understanding, and more into for those who have been trying to get the same function but couldn't get it... and the focus of this post is for the challenges most of us been trying to get the REST API to work in forms for getting the list items or/and the UserProfile... there are many other post already demonstrated how to set value to form controls which I have ignored it in this post. UserProfile is one of the popular one and I was searching the solution with discussion left opened and unsolved since years back, and got my attention to provide the script that works.


I totally get the assumptions. 

I do however think that this sort of functionality is something a lot of less technical users would want and in the absence of a baked in control from Nintex, then seeing they can do this but not necessarily knowing how to, would be really frustrating to them.


Thanks for this, it is exactly what I needed.

I'm trying use it(copied and pasted) in an environment like yours, even with the same App Version (NFO 1.2.3.0). But I'm getting this error: "Your domain doesn't match the expected domain for this app deployment.".

Any idea of what could be happening here?

Thanks


Which script? Grtting from list or user profile? The print statement will cause an infinite loop, that is showing how to get the returned data sample, you will need to substitute it with other script or see how you want to assign or make use of the returned data. It will show the result in the dialog box but just that you will need to close the browser to end it.

if it is usr profile, make sure u have user profile up in ur environment...


Nice post!! This is gold Kok Koon Gan‌!!


Hi,

I am (and I suspect many are) borrowers of script, but cannot immediately see how I can use it in forms. This looks really useful (particularly the user profile info), but to be useable to folks like me and other borrowers, we'd really need to have some tips on implementing this script.

Many thanks.


Hi Shaun,

I have tried to make it as easy as possible for anyone to follow, the script is either success or with error, where with the success execution, i have tried to 'alert' the result with all the properties values of a user profile, which you can take to set or assign to form control(s).

Agreed and it is encouraging to take, understand, and apply existing script with your own needs, there is no way something someone shared will be fit 100% to your needs. As such i think you will still need to study how the script works and amend according to your use.

As it named, the script is to get you a user profile based on the search example, the 'alert' gives you idea how to reference to propert(ies) of the profile. Please note that you will need to remove the 'alert' as it will lead to infinite run causing the form to never end loading.

Let us know what is going nclear, maybe we will be able to point you with more details.

Regards,

Get Outlook for iOS<https://aka.ms/o0ukef>


Thank you for the fast reply. As I have done with other more technical folks' brilliant workarounds - I will 'give it a blast' and let you know where I need pointers.

And then, if I have time, I will try to use it in some kind of document - so as to be useful for folks like me (and as a reference to others in my company who would appreciate the guide).

Cheers,

Shaun


Hi Dario Alvarez‌,

Are you able to find a solution for this error? I ran in to this issue now and am looking around for help.

Kok Koon Gan‌,

I used the first script, getting items from list. I suspect the problem is with the App domain of the Nintex forms when we register on the SharePoint online site. 

Thanks


   you can fetch the user profile properties using a custom JavaScript code. The first step is to grant the Nintex Forms App the permission to query the user profile service.

You need to be the administrator of your tenant in order to perform the following steps :

  • Obtain the app identifier for the “Nintex Forms for Office 365” ( 1. Click the Settings gear icon 2. Then Select Site Settings 3. Under Users and Permissions, click Site app permissions 4. Under the App Display Name search for “Nintex Forms for Office 365”  5. Get the relevant App Identifier e between “i:0i.t|ms.sp.ext|” and “@” ]
  • Once you get the App Identifier for “Nintex Forms for Office 365” , navigate to “https://your SharePoint Site/_layouts/15/appinv.aspx” and paste the ID p that you obtained from the above step ] under the App id
  • Next click on the lookup button  and you will notice that the Title, App Domain and Redirect URL gets filled in automatically
  • Under the Permission Request XML paste the following XML code :

<AppPermissionRequests><AppPermissionRequest Scope=”http://sharepoint/social/tenant&#8221; Right=”Read” />
<AppPermissionRequest Scope=”http://sharepoint/content/tenant&#8221; Right=”Write” />
</AppPermissionRequests>

Once you click create , the trust message will pop-up . 

  • Click on "Trust it"
  • “Nintex Forms for Office 365” now has the permissions to call the user profile service.
  • Now go to your Nintex forms and if you want to get the current logged in users name, switch to the the Nintex Form designer , double click the text box control to open the control settings , and in the default value source choose specify default value ; select Current User (Display Name) from the Insert Reference option located at the right of the canvas > the design area ].
  • Under Advanced –> Store Client ID in JavaScript variable select Yes and give a               unique Client ID JavaScript variable name
  • Now if you need to fetch the other properties on the Employee Name.
  • We can achieve this with the following JavaScript code
  • Common Code (Add this code inside the Site Assets folder and name it “sp.userprofile.js“)

    —————————————————————————————————————————————–

    function SPUserProfile(strAccountName, OnComplete, OnError) {
    var currentObject = this;
    var userprofile = null;

    this.getProperty = function (propertyName) {
    if (this.userprofile == null) {
    propertyValue = “Userprofile not initialized or error fetching user profile”;
    } else {
    var propertyValue = NWF$.grep(this.userprofile.d.UserProfileProperties.results, function (k) {
    return k.Key == propertyName;
    });
    if ((propertyValue == null) || (propertyValue.length == 0)) {
    propertyValue = null;
    }
    }
    return propertyValue;
    }

    this.getDisplayName = function () {
    return this.userprofile.d.DisplayName;
    }

    this.getDepartment = function () {
    var propVal = this.getProperty(“Department”);
    if (propVal == null) {
    return ”;
    } else {
    return propVal{0].Value;
    }
    }

    this.getMobilePhone = function () {
    var propVal = this.getProperty(“MobilePhone”);
    if (propVal == null) {
    return ”;
    } else {
    return propValn0].Value;
    }
    }

    this.getTitle = function () {
    return this.userprofile.d.Title;
    }

    this.getEmail = function () {
    return this.userprofile.d.Email;
    }

    function execCrossDomainRequest() {

    if ((SP == null) || (SP.RequestExecutor == null)) {
    setTimeout(execCrossDomainRequest, 500);
    } else {
    var url = appweburl + “/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(@v)?@v='” + encodeURIComponent(strAccountName) + “‘”;
    var requestHeaders = {
    “Accept”: “application/json;odata=verbose”
    };
    var executor = new SP.RequestExecutor(appweburl);
    executor.executeAsync({
    url: url,
    contentType: “application/json;odata=verbose”,
    method: “GET”,
    headers: requestHeaders,
    success: function (data) {
    currentObject.userprofile = JSON.parse(data.body);
    OnComplete(currentObject);
    },
    fail: function (error) {
    userprofile = null;
    OnError(error);
    },
    });
    }
    }
    var appweburl = decodeURIComponent(getQueryStringParameter(“SPAppWebUrl”));
    NWF.FormFiller.Events.RegisterAfterReady(function () {
    execCrossDomainRequest();
    });
    }


Hi Ravish Verma

Thanks a lot for your reply. My issue is not related to the result, but the domain issue "Your domain doesn't match the expected domain for this app deployment." error, when the REST API is being called from Nintex form.

The app has enough permissions on the site collection to retrieve the list item data.

What I need to understand is the App Domain, and the redirect URL which are given when the Nintex forms app is registered on sharepoint online site. I see this as "formso365.nintex.com" which seems to be correct.

But on digging deep on the error thrown, it seems that the app for Nintex is registered on the given domain, but the REST call is being made from the APP web URL.

Regards


Hope this helps:

Suhail Cloud: "Your domain doesn't match the expected domain for this app deployment." issue in provider hosted add-in 


Thank you Kok Koon Gan‌,

For those who are asking about script, I want to explain the general purpose of the client side code above:

This is the concept of SharePoint provider hosted app. That means when SharePoint apps are hosted on remote servers and want to access SharePoint Tenant (Nintex O365 Forms are playing the role of SharePoint provider hosted apps).

The only way to do this from server side code is to use OAuth access token for authorization.

Since we are not able to access the server side code of Nintex O365 Forms, SharePoint offers a proxy page for wiring client side (Browsers) cross domains calls. This technology embeds the JavaScript "postMessage()" function for communicating between windows & trusted iframes hosted on SharePoint isolated web called app web.

This technologie is called cross-domain library and it is offering a workaround for the browser restriction of cross domains calls via HTTP/HTTPS Get requests.

If anyone needs a detailed explanation about the code please let me know.

BR,


Did you manage to solve the issue? I'm having the same problem.

Thanks


Reply