Technical Articles
Part 2: Start Workflow from your HTML5 application
In my previous blogs, you learnt how to integrate your custom application UI as user task in workflow that is then shown in My Inbox app. While this is one part of the story, in another part you may want to start the workflow from your external user interface or any SAP Cloud based application.
You have modelled the workflow and deployed it in SAP Cloud Platform. Now, how will the workflow be triggered ? – It could be via an external application or other SAP Cloud Applications. For example: when the user form is filled and a button is clicked then a workflow has to be started – say an approval workflow for leave or approval for travel expenses or workflow for asset repair or extended approval workflow from SAP SuccessFactors application when the new hire is created etc.
From external application you can start the workflow by using publicly available Workflow Runtime API and making a small configuration in your external application. From SAP Cloud Applications, you can either directly call the workflow REST-based service via HTTP/HTTPS protocol or via SAP Cloud Integration service. For more details on the latter, you can refer my blog
⇒ There are two separate blogs on how to start a workflow from custom application for Neo and cloud foundry environment respectively:
- This blog is for Neo Environment
- For Cloud Foundry refer blog
Here you go:
I am assuming you have an SAPUI5 application and have some action defined in the application to start the workflow, say a button click.
- Open the SAPUI5 application in SAP WebIDE Full-stack
- Define the destination route in neo-app.json in routes array:
{ "path": "bpmworkflowruntime", "target": { "type": "destination", "name": "bpmworkflowruntime", "entryPath": "/workflow-service" }, "description": "Workflow Service Runtime" }
- In the button action in Component.js or view.controller.js or where you have the action implementation do the following: (a) write the javascript function to call the API for fetching the XSRF token and (b) write the javascript function to call the API to start the workflow with desired initial payload
_fetchToken: function() { var token; $.ajax({ url: "/bpmworkflowruntime/rest/v1/xsrf-token", method: "GET", async: false, headers: { "X-CSRF-Token": "Fetch" }, success: function(result, xhr, data) { token = data.getResponseHeader("X-CSRF-Token"); } }); return token; }
» where URL is <workflow-runtime-destination>/rest/v1/xsrf-token. You can find the destination in Connectivity –> Destinations in SAP Cloud Platform cockpit.
» bpmworkflowruntime is the default destination with ApptoAppSSO authentication type
» For more information on the workflow runtime API, refer the official API documentation
_startInstance: function(token) { var model = this.getView().getModel(); var inputValue = model.getProperty("/text"); $.ajax({ url: "/bpmworkflowruntime/rest/v1/workflow-instances", method: "POST", async: false, contentType: "application/json", headers: { "X-CSRF-Token": token }, data: JSON.stringify({ definitionId: <your workflow ID>, context: { text: inputValue } }), success: function(result, xhr, data) { model.setProperty("/result", JSON.stringify(result, null, 4)); } }); }
» <your workflow ID> is the ID workflow. You can open the workflow SAP Web IDE and see the properties of the workflow to find the ID.
» inputValue is the initial payload with which the workflow starts. It can be your entire application model, a subset of your model or a completely new model.
» The only thing you have to ensure that the data model you pass must be of JSON type as the workflow API works on JSON body.
- Finally, implement the button action to get the CSRF token and then call the public workflow runtime API to start the workflow with the token:
buttonAction: function() { var token = this._fetchToken(); this._startInstance(token); }
Once the action is performed and the workflow has started successfully, you will see the response from API as:
{ id =13, definitionId=LeaveRequestWorkflow, definitionVersion=2, subject=Leave Request for Alice, businessKey=11203, status=RUNNING, startedAt=2017-12-03:40:60:40.000Z, startedBy=Lorin, completedAt=null }
Previous Related Blogs on Neo Environment
Understanding Custom UI Integration with SAP Cloud Platform Workflow
Part1A: Build your Custom HTML5 application in SAP WebIDE for Workflow
Part1B: Using your Custom HTML5 application as User Task in Workflow
Part1C: Working with Task APIs in your Custom HTML5 application
Hi Archana,
Is it possible to use the workflowInstanceId as part of the business-key?
I have tried to set-up the business key using $.info.workflowInstanceId, but it is not being evaluated as it seems.
Hello Christian,
Business key can be defined only based on the workflow context. For Example: ${context.OrderID} etc. What is the need of defining the workflowinstanceid as business key?
Hello Archana,
Thanks for your reply.
We would need it in order to correlate the intermediate messages in bigger processes. The problems we see with using the context information are that:
a) we don't always have a clear business key in the context data
b) sometimes we require the same intermediate message event in one process using different correlation conditions (for signal-type of events)
c) different subprocesses might have different data available for callbacks to the main process. If we only have the context data as correlation condition this might not fit the data available in the subprocesses
d) Broadcasts would require different correlation conditions as compared to intermediate message events only addressing one concrete instance
Therefore we would see the ability to use the workflowInstanceId as an additional correlation criteria as highly beneficial.
Hi Christian,
yes, I fully understand the request.As of today it is not possible to set the value of the business key after instance start. We are planing to enable this in the future and then you will be able to set the business key value based on the instance id.
However, this sounds more like a workaround to me. I think what you actually need, is to be able to send messages to workflow instances based directly on the workflow instance id. Is this assumption correct? If yes, please let me know and I will prioritize it accordingly.
Best regards,
Krassimir
Hi Krassimir,
Thank you for your feedback!
If I understand you correctly, you would enable an option no intermediate message event level to either correlate according to the business key or the workflow instance ID or both, right?
I think that would be a good step in order to resolve some of the cases mentioned above.
The ideal and most flexible solution would probably be if we could define correlation conditions based on context information (including header information like workflow instance Id) using logical expressions for each intermediate message event (similar to Process Orchestration).
Best regards,
Christian
Hi Christian,
yes, this is correct, we plan to have multiple options for matching a message to a workflow instance, however I cannot give you concrete timeline as of today.
Best regards,
Krassimir
Hi Archana,
Where can i see the list of completed processes?(Like Manage Process in NWA).
In “Workflow Monitor” tile, I cannot see “COMPLETED” processes. When I see the Network logs of Workflow Monitor, I see that the service is called only with the below “RUNNING/ERROR/SUSPENDED” parameters. Is this expected?
https://flpportal-p1234567trial.dispatcher.hanatrial.ondemand.com/sap/fiori/bpmworkflowmonitor/wfs/v1/workflow-instances?%24top=100&status=RUNNING&status=ERRONEOUS&status=SUSPENDED&containsText=
When i try the below URL, I see all the completed workflow instances.
https://flpportal-p1234567trial.dispatcher.hanatrial.ondemand.com/sap/fiori/bpmworkflowmonitor/wfs/v1/workflow-instances?$&status=COMPLETED
Thanks,
Shilpa.
Yes Shilpa,
Completed instances cannot be seen via Monitor Workflow app. This feature is currently under development and you would be able to soon filter (from all the available instances) for completed workflow instances as well. For now, you can only use Workflow Instance APIs to get the completed instances (which you already did :))
Regards,
Archana
Thank you Archana. Any hint on when the enhancements to view completed process be available to us?
Regards,
Shilpa
Excelente post, gracias!
Hi Archana,
It was well documented. Great job.
Regards
Guru
The hyperlink for API documentation does not work. Could you please fix it? Thanks!
Regards,
Kumud
Thanks Kumud for pointing this out. I have updated the link
Hi Archana,
Thanks for your help on cloud workflow API, I tried to start the workflow instance using your tip, but as of now, no luck, I am going wrong at some point.
I will explain my scenario.
I have a form with 3 fields , and a submit button, to start the workflow instance and send the data to the backend using the oData service.
Screen shot for your reference.
I have added the code like for startinstance, which is given below.
--------------
_startInstance: function (token) {
var model = this.getView().getModel("myModel");
var tableName = model.read("/staff");
var oDataEntry = {};
oDataEntry.STAFFID = this.getView().byId("IdStaff").getValue();
oDataEntry.STAFFNAME = this.getView().byId("IdName").getValue();
oDataEntry.EMAIL = this.getView().byId("IdmyEmail").getValue();
$.ajax({
url: "/bpmworkflowruntime/rest/v1/workflow-instances",
method: "POST",
async: false,
contentType: "application/json",
headers: {
"X-CSRF-Token": token
},
data: JSON.stringify({
definitionId: " StaffWorkFlow",
context: {
text: oDataEntry
}
}),
success: function (result, xhr, data) {
model.setProperty("/result", JSON.stringify(result, null, 4));
}
});
}
------------------------------------------
My odata service to create the record was like this
==========================
createStaffEntry: function () {
var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
var oDataEntry = {};
oDataEntry.STAFFID = this.getView().byId("IdStaff").getValue();
oDataEntry.STAFFNAME = this.getView().byId("IdName").getValue();
oDataEntry.EMAIL = this.getView().byId("IdmyEmail").getValue();
this.getView().getModel("myModel").create("/STAFF", oDataEntry, {
success: function (oData, response) {
// MessageToast.show("New Staff Created Successfull");
oRouter.navTo("confirmView");
},
error: function (oError) {
MessageToast.show("Create unSuccessfull");
}
});
}
==========================
I want to achieve the same ( create the record and start the workflow) from startInstance function, which, I am unable to do, Please also mention as to where to add the recipient.
Please share your email id, if you can, for any further help.
Please help.
Ikram
Hello Ikram,
As a suggestion, you can run the API in POSTMAN or any other rest client with the given body, authorization and URL to ensure that what you are running is fine.
Hope that helps,
Archana
Hello, Mohammed Ikram.
Did you manage to solve your problem?
Before starting the workflow, I would like to consume a destination to get information.
How did you add destination to the project?
Thanks in advance
Thanks Archana, I am able to start the workflow using the API, but its not showing in My Inbox.
Please any document, on how to configure and implement the Inbox, to see the workflow task, I tried implementing the using this link, but stick up.
Thanks
Ikram
Hi Archana Shukla,
If i wanted to the Workfow to start with a submission of a form is this possible within the Cloud Platform Workflow service or is my only option to build a HTML5 app?
The use case is we want to collect some information from users and route it for approval. I was hoping we could collect the information in a Form created in the Workflow service that represented the start event but I cannot see how to do this.
Thanks,
Lee
Hello Lee,
You can already create a the Form to start the workflow. Read the what's new of 31st July:
https://help.sap.com/doc/8c8be0fcde064d4d95e958c44bbce34c/Cloud/en-US/b08fc84f976c4bb9ae452e8e7e75f48c.html
Regards,
Archana
Thanks Archana for the reply, good news.
Is this available in Neo or only Cloud Foundry?
Regards,
Lee
Hi Archana,
I am able to successfully call my UI app in the user task.
There are two buttons Approve and Reject and i would like to capture the actions back in WF to proceed further. Can you pls let me know how to capture the result of action back in WF.
I added the following code as shown below but still i am unable to obtain the status.
Can you please let me how to bind the value back to context of WF.
var oPositiveAction = {
sBtnTxt: "Approve",
onBtnPressed: function (e) {
var model = that.getModel();
model.setProperty("/context/status", "X");
//model.refresh(true);
//Call a local method to perform further action
that._triggerComplete(that.oComponentData.inboxHandle.attachmentHandle.detailModel.getData().InstanceID, true,
jQuery.proxy(
//on successful competion, call a local method to refresh the task list in My Inbox
that._refreshTask, that));
}
You can import a workflow sample application in your WebIDE and use it as reference to see how add the button response back to workflow context.
Hi Archana,
We are trying to trigger cloud workflow from SAP UI5 application screen.We have followed your instructions and applied given code in neo-app.json.We are getting below error.
Comma seems to be missing or code not copied correctly. Are you working on Neo or CF?
Thanks Archana.Now error fixed.
Hi Archana,
Every time I try to perform the _fetchToken request, I get an 403 status code. The error says: “User does not have sufficient Privileges”. I’ve tried to do the same thing using Postman and didn’t have any problem. I have the Developer role assigned to my user, do I need any other specific role?
Best regards,
Bruna
Hello Bruna,
If you are working on Neo environment, see here the official documentation on the needed roles and ensure that you have the right roles based on what you are trying to achieve. Also, ensure that the destination configuration have right username and password.
Hi Archana,
I want to start a instance from a UI5 Application. I use POST worklow instance in CF from SAP API Business Hub, but it says "blocked by CORS policy"?
Thanks.
Baris
Use the needed environment variable in your application router to handle CORS:
https://help.sap.com/viewer/65de2977205c403bbc107264b8eccf4b/Cloud/en-US/ba527058dc4d423a9e0a69ecc67f4593.html?q=CORS
Hi Archana,
Great Blog!
I am successful in integrating my custom application UI as user task in workflow that is then shown in My Inbox app. I am able to see the desired info in the details page of My Inbox app. But I see that the images are getting uploaded. I see only the controller folder to be loaded where as the images folder inside my web app is missing. Could you pl. help here.
Thanks
Hi Archana Shukla,.
In my case my application is on cloud foundry and the destination route for my workflow should be in xs-app.json. How can I register this route?
Thanks in advance.
Well I found this way fot my xs-app.json
And I added this destination in cloud foundry
When I run my app I get this error:
Read my new blogs on cloud foundry:
https://blogs.sap.com/2020/08/27/starting-workflow-from-custom-fiori-application-in-cloud-foundry/
Hi!
I took the example project in the tutorial and successfully deployed it.
Now, I need to consume a destination to get information before starting a workflow.
In this example project structure, how do I declare the destination to be used in the initial form?
Thanks in advance.
Hello Tiago,
This blog is focussed on Neo, for CF based example to start the workflow from custom UI you can see this blog
Hello Archana,
Thank you very much for your contribution.
It has been very helpful and I appreciate it.
I would like to ask you one point.
Why does this kind of error occur?
How can I get rid of this error?
If possible, I would appreciate your answer.
Sincerely,
Kai
Hello Kai,
it should be in quotes like "purchasepayment"
Hello Archana,
Thank you very much for your reply.
Thank you for letting me know that I can use quotations.
I'm developing it now following the order of your blog, but I'm new to UI 5 and javascript, and I don't know how to write the steps in 3,4 in a javascript file.
If it is possible, can I get all the code files of the application you created in this blog, or can I see them in some kind of github?
Thank you very much for your time.
Sincerely,
Kai
You can import a workflow sample application in your WebIDE and use it as reference to see how it is done.
Thank you very much for your reply.
I'll check it out.
SIncerely,
Kai
Hi Archana,
I want to call a workflow API ( start_instance ) from ERP system. How can I achieve this? Do I need integration Suite service or config?
API hub documentation gives code snippet for REST based API calls, but can we directly use that code, what are the prerequisites to trigger a workflow in such cases?
Thanks
Prasad
Hello,
I use the MY INBOX app where there is flow of different applications. (ECC, S4, UP, CONCUR). Each flow instantiates a different workflow. We have developed our own views for each flow, with its approval and rejection buttons. The call to approval or rejection services are in the actions of the buttons. Can I activate the MASS APPROVAL version and make these flows work?