I'm using SharePoint 2013 online with Office 365. I would like to create a button in a column of my document library to start a workflow. I have code that works, but have to click the button twice. Ideally this button would allow users to click once for the workflow to fire..
Another Question on the site led me to my current solution (Can I add a start workflow link to a column in a list view?). The message appears after the first click, but doesn't actually start unless I click the button again.
Here is the code for my calculated column, based on Update 2 in the other questions solution:
="<button style=""cursor:pointer;"" onclick=""{"
&"event.preventDefault();"
&"function startWorkflow(itemID, wfName) {"
&" function __startWorkflow() {"
&" var ctx = new SP.ClientContext.get_current(),"
&" wfsManager = SP.WorkflowServices.WorkflowServicesManager.newObject(ctx,ctx.get_web()),"
&" wfSubs = wfsManager.getWorkflowSubscriptionService().enumerateSubscriptionsByList(_spPageContextInfo.pageListId);"
&" ctx.load(wfSubs);"
&" ctx.executeQueryAsync(function () {"
&" wfsEnum = wfSubs.getEnumerator();"
&" while (wfsEnum.moveNext()) {"
&" var wfSub = wfsEnum.get_current();"
&" if (wfSub.get_name() === wfName) {"
&" wfsManager.getWorkflowInstanceService().startWorkflowOnListItem(wfSub,itemID,new Object());"
&" SP.UI.Notify.addNotification('Init Workflow: '+wfName+' on item: '+itemID, false);"
&" }}});}"
&" if (!SP.WorkflowServices) {"
&" var script = document.createElement('script');"
&" script.src = '/_layouts/15/sp.workflowservices.js';"
&" script.onload = __startWorkflow;"
&" document.head.appendChild(script); SP.UI.Notify.addNotification('Testing Workflow: '+wfName+' on item: '+itemID, false);"
&" } else {__startWorkflow();}"
&"}"
&"var TR=this;while(TR.tagName!='TR'){TR=TR.parentNode}"
&"startWorkflow(TR.id.split(',')[1] , 'Test-Update');"
&"}"">Test My Workflow</button>"
I think I'm on the right path, but I'm not sure how to resolve the double click issue.