Friday, May 19, 2017

Run SharePoint Workflow on Button Click in List Views using jsLink and JSOM

*This is for SharePoint Online

Sometimes there are requirements from business where they need a button in list view against each item and once you click on it, it should run a workflow for that particular list item.

Make sure to make below changes before using this code.


  •  Change the name of the workflow to start mentioned in variable "WorkflowName",
  •  replace the siteURL
  • Change the column name against which you want to show the button. I am overriding default 'Edit' button 

 /*  Code Starts*/

/*Reference Files*/
<script src="https://siteURL/SiteAssets/jquery-3.2.1.min.js"></script>
<script src="https://siteURL/_layouts/15/SP.Runtime.js"></script>
<script src="https://siteURL/_layouts/15/sp.workflowservices.js"></script>
<script src="https://siteURL/_layouts/15/wfutility.js"></script>
/**/

var itemID = '';
var ItemGUID = '';
var WFSubscriptionID = '';
var WorkflowName = 'Meetings WF';


function getItems(ListTitle, Id) {
    var d = $.Deferred();

    var url = "/_api/web/lists/getByTitle('" + ListTitle + "')/getItemById(" + Id + ")";
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + url,
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
            "content-Type": "application/json;odata=verbose"
        },
        success: function(data) {
            console.log(data)
            d.resolve(data);
        },
        error: function() {
            d.reject('bad request')
        }
    });

    return d.promise();
}


function GetGUID(z, Id) {
    itemID = Id;
    getItems(z, Id).then(function(data) {

        console.log(data.d.GUID);
        ItemGUID = data.d.GUID;
        GetWFSubscriptionID(ctx.listName, itemID, ItemGUID);
    })
}




function StartWorkflowJsLink(overrideCtx) {

    //overrideCtx.listName = "{88E4FF8A-94E8-40AA-89BE-79A98B1CB370}";
    return '<input type="button" value="Start Workflow" onclick="GetGUID(' + "'" + overrideCtx.ListTitle + "'" + ',' + "'" + overrideCtx.CurrentItem.ID + "'" + ')"/>';

}

function registerListRenderer() {

    var overrideCtx = {};


    overrideCtx.Templates = {};

    overrideCtx.Templates.Fields = {

        'Edit': {
            'View': StartWorkflowJsLink
        }

    };


    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideCtx);
}



ExecuteOrDelayUntilScriptLoaded(registerListRenderer, 'clienttemplates.js');




function GetWFSubscriptionID(ListID, ItemID, ItemGUID) {

    showInProgressDialog();

    var listGuid = "88e4ff8a-94e8-40aa-89be-79a98b1cb370";
    var context = SP.ClientContext.get_current();
    var web = context.get_web();
    var sMgr = new SP.WorkflowServices.WorkflowServicesManager(context, web);
    var sservice = sMgr.getWorkflowSubscriptionService();
    var ssubs = sservice.enumerateSubscriptionsByList(listGuid);
    context.load(ssubs);
    context.executeQueryAsync(
        function() {
            var e = ssubs.getEnumerator();
            while (e.moveNext()) {
                var c = e.get_current();
                if (c.get_name() === WorkflowName) {
                    var subId = c.get_id();
                    WFSubscriptionID = subId;
                    StartWorkflow4(WFSubscriptionID, itemID, ItemGUID);
                }
                //alert("Name :" + c.get_name() + " sID: " + c.get_id());
            };

        },
        function() {

        });




}


var errorMessage = "Something went wrong. To try again, reload the page and then start the workflow.";
var theForm = document.forms['aspnetForm'];
if (!theForm) {
    theForm = document.aspnetForm;
}

function StartWorkflow(iwa) {
    var elIwaStart = document.getElementById("iwaStart");
    elIwaStart.value = iwa;
    theForm.submit();
}
var dlg = null;

function StartWorkflow4(subscriptionId, itemId, itemGuid) {

    var ctx = SP.ClientContext.get_current();
    var wfManager = SP.WorkflowServices.WorkflowServicesManager.newObject(ctx, ctx.get_web());
    var subscription = wfManager.getWorkflowSubscriptionService().getSubscription(subscriptionId);
    ctx.load(subscription, 'PropertyDefinitions');
    ctx.executeQueryAsync(
        function(sender, args) {
            var params = new Object();
            var formData = subscription.get_propertyDefinitions()["FormData"];
            if (formData != null && formData != 'undefined' && formData != "") {
                var assocParams = formData.split(";#");
                for (var i = 0; i < assocParams.length; i++) {
                    params[assocParams[i]] = subscription.get_propertyDefinitions()[assocParams[i]];
                }
            }
            if (itemId) {
                wfManager.getWorkflowInstanceService().startWorkflowOnListItem(subscription, itemId, params);
            } else {
                wfManager.getWorkflowInstanceService().startWorkflow(subscription, params);
            }
            ctx.executeQueryAsync(
                function(sender, args) {
                    closeInProgressDialog();
                    /*var elWf4Start = document.getElementById("wf4Start");
                    elWf4Start.value = 1;
                    theForm.submit();*/
                    window.location.href = window.location.href;
                },
                function(sender, args) {
                    closeInProgressDialog();
                    alert(errorMessage);
                }
            );
        },
        function(sender, args) {
            closeInProgressDialog();
            alert(errorMessage);
        }
    );
}

function closeInProgressDialog() {
    if (dlg != null) {
        dlg.close();
    }
}

function showInProgressDialog() {
    if (dlg == null) {
        dlg = SP.UI.ModalDialog.showWaitScreenWithNoClose("Please wait...", "Waiting for workflow...", null, null);
    }
}

function HandleCheckinBeforeStartWorkflow() {
    var strError = "Please check this document in before starting a workflow.";
    window.alert(strError);
}




/*Code Ends*/

You would be able to see "Start Workflow" button in the overridden column as shown below.


Clicking on the button will run that workflow on the corresponding item.

38 comments:

  1. This looks like what I need but I can't figure out where to put this code to use it.

    ReplyDelete
    Replies
    1. You can use in in content editor webpart and add on the same page where you want to show the buttons.

      Delete
  2. Thanks for this! One question how do I make it go to my initiate form? it just hangs on 'Please wait..' Waiting for workflow.

    ReplyDelete
    Replies
    1. Can you please check is there any error being logged in browser console and share that here.

      Delete
    2. This is what is in the console:
      DOM7011: The code on this page disabled back and forward caching. For more information, see: http://go.microsoft.com/fwlink/?LinkID=291337
      File: AllItems.aspx
      SEC7115: :visited and :link styles can only differ by color. Some styles were not applied to :visited.
      File: AllItems.aspx
      DOM7011: The code on this page disabled back and forward caching. For more information, see: http://go.microsoft.com/fwlink/?LinkID=291337
      File: AllItems.aspx
      HTML1508: Unmatched end tag.
      File: AllItems.aspx, Line: 128, Column: 7
      HTML1512: Unmatched end tag.
      File: AllItems.aspx, Line: 133, Column: 6
      HTML1509: Unmatched end tag.
      File: AllItems.aspx, Line: 134, Column: 5
      SEC7115: :visited and :link styles can only differ by color. Some styles were not applied to :visited.
      File: AllItems.aspx
      DOM7011: The code on this page disabled back and forward caching. For more information, see: http://go.microsoft.com/fwlink/?LinkID=291337
      File: AllItems.aspx
      DOM7011: The code on this page disabled back and forward caching. For more information, see: http://go.microsoft.com/fwlink/?LinkID=291337
      File: AllItems.aspx
      SEC7115: :visited and :link styles can only differ by color. Some styles were not applied to :visited.
      File: AllItems.aspx

      Delete
    3. Simon,
      You need to update the script reference to provide the compete URL.
      https://siteURL/_layouts/15/SP.Runtime.js
      https://siteURL/_layouts/15/sp.workflowservices.js
      https://siteURL/_layouts/15/wfutility.js

      wfutility and sp.workflowservices are not loading.

      Delete
    4. Also please check if the LIST ID and the workflow name is updated

      Delete
    5. Hi Manjot, I have checked all of those and the waiting for workflow dialog still just hangs. My workflow has a initiation form, would this affect it? All just confirming you said I need to check if the LIST ID is updated, are you referring to the 'var listGuid' entry?

      Delete
    6. ok. Please replace
      var wfManager = SP.WorkflowServices.WorkflowServicesManager(ctx, ctx.get_web());
      with
      var wfManager = SP.WorkflowServices.WorkflowServicesManager.newObject(ctx, ctx.get_web());

      I have corrected in the blog as well.
      This will directly run the workflow rather than taking you to initiation form.
      Let me know if you want to go to initiation form rather than directly running the workflow.

      Delete
    7. Hi Manjot, Neither work it still just says please wait and sits there doing nothing.

      Delete
    8. can you please email me your code at manjot.singh057@gmail.com ? Let me take a look and find the issue. Also mention what kind of workflow is it. Nintex or SP Designer ?

      Delete
    9. Hello, I am getting the same results. I would like for the button to open the initiation form but it is hanging on please wait. Do you have any suggestions?

      Thanks.

      Delete
    10. Use this code. I have added this in another blog post.
      http://buildsharepointconcepts.blogspot.com/2018/05/go-to-workflow-initiation-form-on.html

      Delete
    11. Thanks for the quick reply Manjot. Im not using Nintex workflow, just the native workflows. What should this line be?

      var WFPageURL = '/_layouts/15/NintexWorkflow/StartWorkflow.aspx?';

      Delete
    12. Actually I think I figured that part out.

      Thank you so much for all of the help

      Delete
    13. Sorry one other question. Is there a way to embed the button on the display form for an item?

      Delete
  3. This comment has been removed by the author.

    ReplyDelete
  4. How apply this solution for the custom button in the page? Like a input button = < input type="button" value="Start WF" name="Start WF" onclick="..." >

    ReplyDelete
  5. this is creating input buttons only. Please elaborate your requirement

    ReplyDelete
  6. It's incredibly an amazing and key bit of information.I'm in remarkable spirits that you in a general sense offered this confounding information to us.Click Here

    ReplyDelete
  7. We are really grateful for your blog post. You will find a lot of approaches after visiting your post. I was exactly searching for. Thanks for such post and please keep it up. Great work. More information

    ReplyDelete
  8. This short description of CTFO gives you some idea of what the company does: ---
    Changing The Future Outcome also known as CTFO is a reputable (MLM) multi level marketing business in the CBD Oil niche. The primary reason behind their fast growth is that they provide some of the best CBD products in the marketplace. They also provide the products at a low cost for their associates and consumers. Considering that the CBD niche is growing faster and faster every year, it's easy to see why the CTFO network marketing company is growing so fast.CTFO

    ReplyDelete
  9. Online you can see lots of wooden sunglasses variety. All glasses comes in a market with unique design. You can wear on any occassion.homescapes hack

    ReplyDelete
  10. This High Temperature Aging Chamber is widely applied for automotive parts ,electronic and electric products ,components and materials by constant high temperature reliability test.High Temperature Aging Environmental Test Chamber

    ReplyDelete
  11. it's very easy to understand which weblogs as well as web sites utilizing absolutely no connection characteristics within their hyperlinks tend to be DoFollows.rfevents.com.pk

    ReplyDelete
  12. I have been looking to discover a solace or powerful Best ps4 steering to finish this procedure and I think this is the most reasonable approach to do it viably.Textnew post from kitchenscity.com

    ReplyDelete
  13. I have been looking to discover a solace or powerful Best ps4 steering to finish this procedure and I think this is the most reasonable approach to do it viably.http://boyumlaw.com

    ReplyDelete
  14. This is a great article. I am enjoying reading your well-written articles. It looks like you spend a lot of effort and time on your blog. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work.http://moneygrower.co.uk/

    ReplyDelete
  15. { Otherwise, {you can|you are able to|it is possible to|you'll be able to} directly ask Pay - Pal {or other|or any other|or another|and other} {methods to|techniques to|solutions to|ways to} {help you|assist you to|enable you to|allow you to} on phone or through remote desktop software| Some things {to look|to appear|to check|to take a look} out for {are the|would be the|will be the|include the} {availability of|accessibility to|option of|use of} direct {phone numbers|telephone numbers|cell phone numbers|numbers}, instant messaging support, and direct emails| You will never {know exactly|know precisely|understand specifically|specifically} that {what type of|which kind of|what sort of|which} client {you are|you're|you might be|you happen to be} handling {and you have|and you've got|plus you've got|along with} to be prepared {and have|and also have|and possess|and still have} some {bunch of|couple of|few|lot of} {ideas to|suggestions to|tips to|tricks to} {make out|write out|find out|figure out} the solutions pdf data entry services

    ReplyDelete
  16. Thank you very much for writing such an interesting article on this topic. This has really made me think and I hope to read more.Florisis Cluj

    ReplyDelete
  17. I have read your blog it is very helpful for me. I want to say thanks to you. I have bookmark your site for future updates.
    Berufsunfähigkeit Kassel

    ReplyDelete
  18. Very nice blog and articles. I am realy very happy to visit your blog. Now I am found which I actually want. I check your blog everyday and try to learn something from your blog. Thank you and waiting for your new post.
    followpc.com

    ReplyDelete
  19. I wanted to thank you for this excellent read!! I definitely loved every little bit of it. I have you bookmarked your site to check out the new stuff you post.
    Berufsunfähigekits Versicherung Kassel

    ReplyDelete
  20. If you are finding the best web developing company then I'll suggest you to visit web design company denver as from there you can get all professional designer for your website.new york city

    ReplyDelete
  21. Super site! I am Loving it!! Will return once more, Im taking your food additionally, Thanks. Click here

    ReplyDelete
  22. A Course in Miracles: The Message:
    A Course in Miracles the message teaches us that there is a Voice for God in our minds that is always talking to us, telling us that we are: unlimited, one with all life, eternal, and literally invulnerable. That Voice is the Holy Spirit. There is another voice in our minds that we made up that lies to us and tells us we are: limited, separate, mortal, and vulnerable. That voice is the ego. A primary focus of a course in miracle’s message is to teach us how to tell these two voices apart. Once we do that we must choose to listen to the Holy Spirit and trust the Holy Spirit's counsel. We will always hear the voice of the ego while here in the dream but we should not accept its guidance or counsel about anything. In a course in miracle the message is not about the death of the ego, but how to properly relate to it.Frances Xu

    ReplyDelete
  23. Its a great pleasure reading your post.Its full of information I am looking for and I love to post a comment that "The content of your post is awesome" Great work.Florisis Cluj

    ReplyDelete