cancel
Showing results for 
Search instead for 
Did you mean: 
Workflow Hero

Couldn't trigger workflow from JavaScript embedded in Nintext Forms for Office 365

Hi Everyone,

I am working on a Nintex forms for office 365. I want to trigger a workflow on click of a button(which will trigger a javascript function) in Nintext Forms(for Office 365) and once the workflow is completed, I want to navigate to a url.

I am facing challenge while triggering the workflow. The Soap service for Nintex works in 2010 Nintex but it is not working in Nintex for Office 365 environment.

Thanks in advance for your help.

Best regards,

Tushar

Labels: (1)
0 Kudos
Reply
9 Replies
Workflow Hero

Re: Couldn't trigger workflow from JavaScript embedded in Nintext Forms for Office 365

Hi Tushar,

seems like the Nintex Online REST Api doesn't offer anything to help us here. Is it a list workflow you are trying to trigger? Would it be an option to not start the workflow directly but to create a list item via regular SharePoint Online REST endpoint and have the workflow triggered on item creation? I don't really like this as you will have to create an item for actually nothing but at least it would start your workflow.

If anyone has a better idea I'd love to hear that!

Cheers

Philipp

0 Kudos
Accept as Solution Reply
Workflow Hero

Re: Couldn't trigger workflow from JavaScript embedded in Nintext Forms for Office 365

Thanks for your reply ‌.

Actually I want to copy the current item into a new item and navigate the user to edit form of newly created item on click of a button in Nintex form.

That is why I wanted to trigger the workflow on button click, then once the workflow is completed, I want to navigate to the Edit form.

Hope you understand my problem statement here. 

0 Kudos
Accept as Solution Reply
Workflow Hero

Re: Couldn't trigger workflow from JavaScript embedded in Nintext Forms for Office 365

You mean you only need the workflow for copying the item? Can't you use plain REST for creating the item? This way you should be able to create the link to the edit form of the newly created item manually and redirect the user to that page.

Accept as Solution Reply
Workflow Hero

Re: Couldn't trigger workflow from JavaScript embedded in Nintext Forms for Office 365

Philipp Lucas‌, I did the same. Item creation is successful for me. I am struggling at the part where I need to copy the attachments from old Item to new item. 

I ahevd used below referances: 

SharePoint 2013 - Uploading Multiple Attachments To The New Item On List Using JSOM And REST API 

Tech and me: How to copy files between sites using JavaScript REST in Office365 / SharePoint 2013  

But now, when I am using POST, it is throwing an error : ""{"error":{"code":"-2147024883, Microsoft.SharePoint.SPException","message":{"lang":"en-US","value":"The data is invalid. (Exception from HRESULT: 0x8007000D)"}}}""

Please find my code below:


//Function to get Querystring Parameter by name
function getParameterByName(name, url) {
    if (!url) {
        url = window.location.href;
    }
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

var riskProcessing = riskProcessing || {};

riskProcessing.copyService = function ($, listTitle) {
    var self = this;

    self.defaultTab = "1.";

    self.copyItem = copyItem;

    self.listEditFormUrl = "";

    self.listTitle = "Risk Processing";
    var fieldCollection, newListItem, itemUrl, attachmentFilesFromSource, newListItemID, digestValue;

    var attachments = [];
    function copyItem(itemId, newTitle) {
        //debugger;
        digestValue = $('#__REQUESTDIGEST').val();
        riskProcessing.dilog.loading.show(" ", "Copying data from selected item.\nYou will be redirected to the copied item shortly.\nPlease wait...");
        var clientContext = new SP.ClientContext.get_current();
        var web = clientContext.get_web();
        var list = web.get_lists().getByTitle(self.listTitle);
        fieldCollection = list.get_fields();
        clientContext.load(fieldCollection);
        var itemToCopy = riskProcessing.getItemById(list, itemId);
        clientContext.load(list);
        clientContext.load(itemToCopy);

        clientContext.executeQueryAsync(function () {
            var listId = list.get_id().toString().toUpperCase();
            var missingFields = [];
            itemToCopy = riskProcessing.selectFirstItem(itemToCopy);
            //debugger;
            var itemRPClient = itemToCopy.get_item("RPClient");

            //Create New Item and assign the values same as in Copy Workflow
            var itemCreateInfo = new SP.ListItemCreationInformation();
            newListItem = list.addItem(itemCreateInfo);
            newListItem.update();
            clientContext.load(newListItem);
            clientContext.executeQueryAsync(function () {
                //success
                //debugger;
                itemUrl = _spPageContextInfo.webAbsoluteUrl + "/_layouts/listform.aspx?PageType=6&ListId={" + listId + "}&ID=" + newListItem.get_id() + "&Source=" + _spPageContextInfo.webAbsoluteUrl;
                console.warn('itemUrl: ' + itemUrl);
                newListItemID = newListItem.get_id()
                newListItem = list.getItemById(newListItemID);

                //enumerate the list fields and update values
                var fieldEnumerator = fieldCollection.getEnumerator();
                while (fieldEnumerator.moveNext()) {
                    var oField = fieldEnumerator.get_current();
                    //exclude fields
                    if ((!oField.get_readOnlyField())
                        && (oField.get_internalName() != "Attachments")
                        && (!oField.get_hidden())) {
                        //get value of source field

                        try {
                            var sourceVal = itemToCopy.get_item(oField.get_internalName());
                            if (sourceVal != null) {
                                //set value on new item
                                newListItem.set_item(oField.get_internalName(), sourceVal);
                            }
                        }
                        catch (ex) {
                            missingFields.push(oField.get_internalName());
                        }

                    }
                }
                console.log('Missing Fields:')
                console.log(missingFields);
                newListItem.update();
                clientContext.load(newListItem);
                //Update Fields
                newListItem.set_item('Title', 'new title');
                newListItem.update();

                clientContext.executeQueryAsync(function () {
                    //Update success handler function
                    //debugger;

                    var attachmentFolder = web.getFolderByServerRelativeUrl('Lists/Risk Processing/Attachments/' + itemId);

                    attachmentFilesFromSource = attachmentFolder.get_files();

                    clientContext.load(attachmentFilesFromSource);

                    clientContext.executeQueryAsync(function () {
                        //success getting attachments
                        //debugger;
                        var i = 0;
                        var attachmentFilesCount = attachmentFilesFromSource.get_count();

                        var promisesArr = [], promisesArr1 = [];
                        for (var file in attachmentFilesFromSource) {
                            if (attachmentFilesFromSource.itemAt(i) !== undefined && attachmentFilesFromSource.itemAt(i) !== null) {
                               
                                var fileServerRelativeUrl = attachmentFilesFromSource.itemAt(i).get_serverRelativeUrl();
                                var fileName = attachmentFilesFromSource.itemAt(i).get_name();
                                i++;

                                var p = GetAttachmentData(newListItemID, self.listTitle, fileName, fileServerRelativeUrl);
                                promisesArr.push(p);
                            }
                            else {
                                break;
                            }

                        }
                        $.when.apply($, promisesArr).then(function (schemas) {
                            console.log('attachments:'); console.log(attachments);
                            debugger;
                            for (var i = 0; i < attachments.length; i++) {
                                debugger;
                                var attachment = attachments[i];
                                var p1 = UploadFileAsAttachment(attachment.Listname, attachment.ItemID, attachment.Filename, attachment.Body);
                                promisesArr1.push(p1);
                            }

                            $.when.apply($, promisesArr1).then(function (schemas1) {
                                debugger;
                                //GotoEditForm(itemUrl);
                            }, function (e) {
                                debugger;
                                console.log("error while getting promisesArr1");
                            });


                        }, function (e) {
                            console.log("error while getting promisesArr");
                        });
                    }, function () {
                        //failure
                        alert('failure while getting an attachment from source item');
                        riskProcessing.dilog.loading.hide();
                    });
                }, function () {
                    //failure
                    alert('failure while updating an item');
                    riskProcessing.dilog.loading.hide();
                })
            }, function () {
                //failure
                alert('failure while creating new item');
                riskProcessing.dilog.loading.hide();
            })

        }, function () {
            alert("Cannot query seleted item\nPlease reload the page and try again.")
            riskProcessing.dilog.loading.hide();
        });
    }

    function GotoEditForm(itemUrl) {
        //Navigate to Edit Form
        if (window.frameElement && window.frameElement.navigateParent) {
            window.frameElement.navigateParent(itemUrl);
        } else {
            window.location.href = itemUrl;
        }
    }

    function GetAttachmentData(itemID, listname, filename, fileServerRelativeUrl) {
        var deferred = $.Deferred();
        var fileContentUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/GetFileByServerRelativeUrl('" + fileServerRelativeUrl + "')/$value";

        $.ajax({
            url: fileContentUrl,
            type: "GET",
            binaryStringResponseBody: true,
            headers: {
                "accept": "application/json;odata=verbose"
            },
            success: function (data) {
                //binary data available in data.body
                debugger;
                var attachment = {};
                attachment.Filename = filename;
                attachment.Listname = listname;
                attachment.ItemID = itemID;
                attachment.Body = data;
                attachments.push(attachment);
                deferred.resolve(true);
            },
            error: function (err) {
                debugger;
                alert('error while getting file attachment data');
                deferred.reject(err);
            }
        });
        /*
        var executor = new SP.RequestExecutor(appweburl);
        var info = {
            url: fileContentUrl,
            method: "GET",
            binaryStringResponseBody: true,
            success: function (data) {
                //binary data available in data.body
                debugger;
                var result = data.body;
                var attachment = {};
                attachment.Filename = filename;
                attachment.Listname = listname;
                attachment.ItemID = itemID;
                attachment.Body = data.body;
                attachments.push(attachment);
                deferred.resolve(true);
            },
            error: function (err) {
                debugger;
                alert('error while getting file attachment data');
                deferred.reject(err);
            }
        };
        executor.executeAsync(info);
         */

        return deferred.promise();
    }




    function str2ab(str) {
        var buf = new ArrayBuffer(str.length); // 2 bytes for each char
        var bufView = new Uint8Array(buf);
        for (var i = 0, strLen = str.length; i < strLen; i++) {
            bufView[i] = str.charCodeAt(i);
        }
        return buf;
    }

   

    //Upload a File as attachment
    function UploadFileAsAttachment(listname, id, filename, buffer) {
        var deferred = $.Deferred();

        // var bytes = str2ab(buffer);
        // var binary = '';
        // for (var b = 0; b < bytes.length; b++) {
        //     binary += String.fromCharCode(bytes);
        // }
         debugger;
        var binary= buffer;
      
        //Attach file as attachment - Start
        var postRequestUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('" + listname + "')/items(" + id + ")/AttachmentFiles/add(FileName='" + filename + "')";

        $.ajax({
            type: "POST",
            url: postRequestUrl,
            headers: {
                "Accept": "application/json; odata=verbose",
                "X-RequestDigest": $('#__REQUESTDIGEST').val()
            },
            contentType: "application/json;odata=verbose",
            binaryStringRequestBody: true,
            body: binary,
            success: function (data) {
                debugger;
                console.log(data + ' uploaded successfully');
                deferred.resolve(data);
            },
            error: function (err) {
                debugger;
                console.log(filename + "not uploaded error");
                deferred.reject(err);
            },
            state: "Update"
        });

        /*
            var reqExec = new SP.RequestExecutor(appweburl);
        reqExec.executeAsync({
            url: postRequestUrl,
            method: "POST",
            headers: {
                "Accept": "application/json; odata=verbose",
                "X-RequestDigest": digestValue
            },
            contentType: "application/json;odata=verbose",
            binaryStringRequestBody: true,
            body: binary,
            success: function (data) {
                debugger;
                console.log(data + ' uploaded successfully');
                deferred.resolve(data);
            },
            error: function (err) {
                debugger;
                console.log(filename + "not uploaded error");
                deferred.reject(err);
            },
            state: "Update"
        });
         */

        //Attach file as attachment - End
        return deferred.promise();
    }

}

riskProcessing.dilog = (function () {
    var loadingDataDilog = null;

    function showLoadingDilog(headerText, bodyText) {
        try {
            if (!loadingDataDilog) {
                loadingDataDilog = SP.UI.ModalDialog.showWaitScreenWithNoClose(headerText, bodyText, 200, 300);
            }
        } catch (e) {

        } finally {

        }
    }

    function hideLoadingDilog() {
        try {
            if (loadingDataDilog) {
                loadingDataDilog.close();
                loadingDataDilog = null;
            }
        } catch (e) {

        } finally {

        }
    }


    return {
        loading: {
            show: function (header, body) {
                showLoadingDilog(header, body);
            },
            hide: function () {
                hideLoadingDilog();
            }
        }
    }

})();

riskProcessing.getItemById = function (list, itemId) {
    var query =
        "<View>" +
        "<Query>" +
        "<Where>" +
        "<Eq>" +
        "<FieldRef Name='ID'/>" +
        "<Value Type='Number'>" + itemId + "</Value>" +
        "</Eq>" +
        "</Where>" +
        "</Query>" +
        "</View>";

    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml(query);

    return list.getItems(camlQuery);
}

riskProcessing.selectFirstItem = function (collection) {
    var result = null;
    var enumerator = collection.getEnumerator();

    if (enumerator.moveNext()) {
        result = enumerator.get_current();
    }

    return result;
}‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍
0 Kudos
Accept as Solution Reply
Workflow Hero

Re: Couldn't trigger workflow from JavaScript embedded in Nintext Forms for Office 365

Have you tried debugging the code via your browsers dev tools?

0 Kudos
Accept as Solution Reply
Workflow Hero

Re: Couldn't trigger workflow from JavaScript embedded in Nintext Forms for Office 365

Yeah. I did. I have embedded this JavaScript code in a SharePoint page with the help of Content Editor Web Part.

I have the issue at the post call shown below which gives me error: ""{"error":{"code":"-2147024883, Microsoft.SharePoint.SPException","message":{"lang":"en-US","value":"The data is invalid. (Exception from HRESULT: 0x8007000D)"}}}""

var binary= buffer;//this is the data I got from List Item attachment Attachment file 
      
        //Attach file as attachment - Start
        var postRequestUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('" + listname + "')/items(" + id + ")/AttachmentFiles/add(FileName='" + filename + "')";

        $.ajax({
            type: "POST",
            url: postRequestUrl,
            headers: {
                "Accept": "application/json; odata=verbose",
                "X-RequestDigest": $('#__REQUESTDIGEST').val()
            },
            contentType: "application/json;odata=verbose",
            binaryStringRequestBody: true,
            body: binary,
            success: function (data) {
                debugger;
                console.log(data + ' uploaded successfully');
                deferred.resolve(data);
            },
            error: function (err) {
                debugger;
                console.log(filename + "not uploaded error");
                deferred.reject(err);
            },
            state: "Update"
        });
0 Kudos
Accept as Solution Reply
Workflow Hero

Re: Couldn't trigger workflow from JavaScript embedded in Nintext Forms for Office 365

What file have you tried to upload? Did you make sure there is content in the file? For example you cannot upload empty word docs into sharepoint.

0 Kudos
Accept as Solution Reply
Workflow Hero

Re: Couldn't trigger workflow from JavaScript embedded in Nintext Forms for Office 365

Hi Phillip,

There is a content in the file. It is not empty.

By the way, do you have any idea how we can copy the attachments from one item to another using REST of JSOM in SharePoint online? 

Thanks in advance.

0 Kudos
Accept as Solution Reply
Workflow Hero

Re: Couldn't trigger workflow from JavaScript embedded in Nintext Forms for Office 365

0 Kudos
Accept as Solution Reply