none
Workflow doesnt start after one click on button RRS feed

  • Question

  • Hello!
    I have SharePoint list with calculated column, which contains script to make it a button. Button is running workflow on click.

    ="<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('NOTIFICATION_FOR_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);"
    &"  } else {__startWorkflow();}"
    &"}"
    &"var TR=this;while(TR.tagName!='TR'){TR=TR.parentNode}"   
    &"startWorkflow(TR.id.split(',')[1] , 'YOUR_WORKFLOW_TITLE_GOES_HERE');"
    &"}"">NAME_OF_BUTTON</button>"

    The workflow only launches if you double-click the button. A single click displays the Notification but does not start the workflow.
    Also it launch after first click if I am doing it for more than one item on list, but in this case it is working for every clicked item except the last one.
    Script is working fine, the thing is in workflow somehow as I think.
    Changing the workflow doesn't help, issue appears for every workflows and for every items (new ones, old ones and etc).
    Could you please help me to find the solution or some workarounds?

    Monday, December 9, 2019 11:36 AM

Answers

  • Hi Ermakov Maxim,

    Eventually we fixed this issue after a lot of tests. Below is my code and test:

    1, Prepare calculated column and buttons

    2, Add the following code:

    <script language="javascript" type="text/javascript"
        src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    
    <script language='javascript' type='text/javascript'>
        $(document).ready(function () {
            window.demo={};
            SP.SOD.executeFunc('sp.js', 'SP.Utilities.Utility.getLayoutsPageUrl', init);
            
        });
    
        function init() {
            $.getScript(SP.Utilities.Utility.getLayoutsPageUrl('sp.workflowservices.js'), function () {
                $("button[name='caluatedbtn']").click(StartWF);
            });
        }
    
        function StartWF() {
            console.log('--start01');        
            demo.clientContext = new SP.ClientContext.get_current();
            demo.wfsManager = SP.WorkflowServices.WorkflowServicesManager.newObject(demo.clientContext, demo.clientContext.get_web());
            demo.wfSubs = demo.wfsManager.getWorkflowSubscriptionService().enumerateSubscriptionsByList(_spPageContextInfo.pageListId);
            demo.clientContext.load(demo.wfsManager);
            demo.clientContext.load(demo.wfSubs);
    
            demo.clientContext.executeQueryAsync(onQuerySucceeded,onQueryFailed);         
        }
    
        function onQuerySucceeded() {
            console.log('--start-suc');
            var wfsEnum = demo.wfSubs.getEnumerator();
            while (wfsEnum.moveNext()) {
                var wfSub = wfsEnum.get_current();
                if (wfSub.get_name() === 'test008') {
                    console.log('--start05');
                    demo.wfsManager.getWorkflowInstanceService().startWorkflowOnListItem(wfSub, 7, new Object());
                    SP.UI.Notify.addNotification('NOTIFICATION_FOR_ITEM:', false);
                    demo.clientContext.executeQueryAsync(function(){
                        console.log("Started OK");
                    });                
                }
            }
        }
    
        function onQueryFailed() {
            alert('fail');
        }
    
    </script>
    
    <h2>this is test</h2>    
    

    Result:

    The reason why we need double click is that we did not submit changes after it started workflow:

    workflowInstanceService.StartWorkflowOnListItem(firstWorkflowAssociation, listItem.Id, startParameters);
    ctx.ExecuteQuery();

    *Please not forgot to replace the info such as workflow name/item id with your own values. 

    Best Regards,

    Baker Kong


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.

    SharePoint Server 2019 has been released, you can click  here to download it.
    Click here to learn new features. Visit the dedicated forum to share, explore and talk to experts about SharePoint Server 2019.

    • Marked as answer by Ermakov Maxim Wednesday, December 18, 2019 7:50 AM
    Tuesday, December 17, 2019 8:03 AM

All replies

  • Hi Ermakov Maxim,

    Here I inserted some snippet code into script editor web part and tested the functionality of running a workflow by clicking a button. However it works fine in my environment, I am not able to reproduce this situation. Could you please share more info about how to place the above code? is there any error message? screenshots and steps are appreciated! 

    Best Regards,

    Baker Kong


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.

    SharePoint Server 2019 has been released, you can click  here to download it.
    Click here to learn new features. Visit the dedicated forum to share, explore and talk to experts about SharePoint Server 2019.

    Tuesday, December 10, 2019 9:42 AM
  • Hi,
    This code actually is not on the script editor, it is in the calculated column in list
    No error appears, just notification appears, workflow doesn't start.

    Notification is work as intended and defined in script.

    The thing is that workflow starts, but not after one click on one item which is not that great.

    Sadly, I can not put screenshots here because of account verifying process.

    Thank you in advance for attention!

    Wednesday, December 11, 2019 6:34 AM
  • Hi Ermakov Maxim,

    Eventually we fixed this issue after a lot of tests. Below is my code and test:

    1, Prepare calculated column and buttons

    2, Add the following code:

    <script language="javascript" type="text/javascript"
        src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    
    <script language='javascript' type='text/javascript'>
        $(document).ready(function () {
            window.demo={};
            SP.SOD.executeFunc('sp.js', 'SP.Utilities.Utility.getLayoutsPageUrl', init);
            
        });
    
        function init() {
            $.getScript(SP.Utilities.Utility.getLayoutsPageUrl('sp.workflowservices.js'), function () {
                $("button[name='caluatedbtn']").click(StartWF);
            });
        }
    
        function StartWF() {
            console.log('--start01');        
            demo.clientContext = new SP.ClientContext.get_current();
            demo.wfsManager = SP.WorkflowServices.WorkflowServicesManager.newObject(demo.clientContext, demo.clientContext.get_web());
            demo.wfSubs = demo.wfsManager.getWorkflowSubscriptionService().enumerateSubscriptionsByList(_spPageContextInfo.pageListId);
            demo.clientContext.load(demo.wfsManager);
            demo.clientContext.load(demo.wfSubs);
    
            demo.clientContext.executeQueryAsync(onQuerySucceeded,onQueryFailed);         
        }
    
        function onQuerySucceeded() {
            console.log('--start-suc');
            var wfsEnum = demo.wfSubs.getEnumerator();
            while (wfsEnum.moveNext()) {
                var wfSub = wfsEnum.get_current();
                if (wfSub.get_name() === 'test008') {
                    console.log('--start05');
                    demo.wfsManager.getWorkflowInstanceService().startWorkflowOnListItem(wfSub, 7, new Object());
                    SP.UI.Notify.addNotification('NOTIFICATION_FOR_ITEM:', false);
                    demo.clientContext.executeQueryAsync(function(){
                        console.log("Started OK");
                    });                
                }
            }
        }
    
        function onQueryFailed() {
            alert('fail');
        }
    
    </script>
    
    <h2>this is test</h2>    
    

    Result:

    The reason why we need double click is that we did not submit changes after it started workflow:

    workflowInstanceService.StartWorkflowOnListItem(firstWorkflowAssociation, listItem.Id, startParameters);
    ctx.ExecuteQuery();

    *Please not forgot to replace the info such as workflow name/item id with your own values. 

    Best Regards,

    Baker Kong


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.

    SharePoint Server 2019 has been released, you can click  here to download it.
    Click here to learn new features. Visit the dedicated forum to share, explore and talk to experts about SharePoint Server 2019.

    • Marked as answer by Ermakov Maxim Wednesday, December 18, 2019 7:50 AM
    Tuesday, December 17, 2019 8:03 AM
  • Thank you a lot! Works perfect from first click!

    Could you please tell me how to make this code get current item ID automatically?

    Wednesday, December 18, 2019 8:24 AM
  • Hi Ermakov Maxim,

    Below is my test workflow:

    I think your original code could get id correctly. 

    Jquery version:

    //@this, event source button
    $(this).closest("tr");

    Or you can add id column to the list view then directly get item id. 

    More reference docs:

    Best Regards,

    Baker Kong


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.

    SharePoint Server 2019 has been released, you can click  here to download it.
    Click here to learn new features. Visit the dedicated forum to share, explore and talk to experts about SharePoint Server 2019.

    Wednesday, December 18, 2019 8:48 AM
  • Hello!
    I tried this code and after some changes it fits perfectly!
    But there is one thing that doesn't feel great - when I am using any filters, grouping or sorting on the list buttons doesn't work because function initiates on "$(document).ready". To fix this i put in code this fragment:

    $(document).dblclick(function(){
        window.demo={};
        SP.SOD.executeFunc('sp.js', 'SP.Utilities.Utility.getLayoutsPageUrl', init);      
    });
    So the buttons start work on "ready" or after double click (also tried on click) on page, but it is not perfect way to fix, because users sometimes clicking on page a lot and then receiving multiple notifications for one button click. Also I am not sure that it is good idea to launch same workflows so many times for one item at once.
    Is there a better solution for list views with grouping, filtering or sorting?
    • Edited by Ermakov Maxim Friday, December 20, 2019 4:22 AM Added a bit more info
    Friday, December 20, 2019 4:15 AM
  • Hi Ermakov Maxim,

    You can add all event function to 'onclick' attr like your original code. Or have a try following code:

    1, Prepare button:

    ="<button name='caluatedbtn' style='cursor:pointer;' type='button' onclick='StartWF()'>Start WF</button>"

    2, Insert code:

    <script language="javascript" type="text/javascript"
        src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    
    <script language='javascript' type='text/javascript'>
        
    	ExecuteOrDelayUntilScriptLoaded(initdata, "sp.js");
    	
    	function initdata() {
            window.demo={};
            if (!SP.WorkflowServices){
    			$.getScript(SP.Utilities.Utility.getLayoutsPageUrl('sp.workflowservices.js'), null);		
    		}        
        }
    
        function StartWF() {
            console.log('--start01');        
            demo.clientContext = new SP.ClientContext.get_current();
            demo.wfsManager = SP.WorkflowServices.WorkflowServicesManager.newObject(demo.clientContext, demo.clientContext.get_web());
            demo.wfSubs = demo.wfsManager.getWorkflowSubscriptionService().enumerateSubscriptionsByList(_spPageContextInfo.pageListId);
            demo.clientContext.load(demo.wfsManager);
            demo.clientContext.load(demo.wfSubs);
    
            demo.clientContext.executeQueryAsync(onQuerySucceeded,onQueryFailed);         
        }
    
        function onQuerySucceeded() {
            console.log('--start-suc');
            var wfsEnum = demo.wfSubs.getEnumerator();
            while (wfsEnum.moveNext()) {
                var wfSub = wfsEnum.get_current();
                if (wfSub.get_name() === 'test008') {
                    console.log('--start05');
                    demo.wfsManager.getWorkflowInstanceService().startWorkflowOnListItem(wfSub, 7, new Object());
                    SP.UI.Notify.addNotification('NOTIFICATION_FOR_ITEM:', false);
                    demo.clientContext.executeQueryAsync(function(){
                        console.log("Started OK");
                    });                
                }
            }
        }
    
        function onQueryFailed() {
            alert('fail');
        }
    
    </script>
    
    <h2>this is test</h2>    
    

    Best Regards,

    Baker Kong

    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.

    SharePoint Server 2019 has been released, you can click  here to download it.
    Click here to learn new features. Visit the dedicated forum to share, explore and talk to experts about SharePoint Server 2019.

    Friday, December 20, 2019 9:08 AM