1

I have a task list that I have created a customised 'newform' for. I am hoping to add a button to this form which when clicked will change a field from no to yes (for the current item). This change in the fields value will be used to trigger a list workflow. Please could anyone advise how to achieve this.

Thanks

  • Is there a reason you want a custom button instead of an OOTB checkbox? – Erin L Apr 5 '16 at 13:08
1

It sounds like you want to create a custom button on the NewForm that triggers a workflow on the item. This can be accomplished with JavaScript.

Since you are creating a custom form I assume you know how to add a <script> block to it. I will also assume the workflow you want to trigger is an SPD2013 workflow (triggering a 2010 workflow with JavaScript uses different methods from what is below).

Importantly, creating or updating a list item using JSOM/CSOM does not trigger the workflow "On Creation" or "On Edit" events, so there is no need to set a field in the item to "Yes" before starting a workflow on the item. Instead, you can just start the workflow immediately once the button is pressed, but you must then manually code the behavior that happens afterwards (for example, something on the page to let the user know the workflow started). That is outside the scope of this post.

In order to use the JavaScript below, you need to know the Subscription ID of the workflow you want to trigger. You can find that using the following PowerShell (run in the SharePoint Management Shell):

$sourceWebURL = '<URL>'

$sourceListName = '<List Name>'

$TargetWorkflow = '<Workflow Name>'

$spSourceWeb = Get-SPWeb $sourceWebURL

$spSourceList = $spSourceWeb.Lists[$sourceListName]

# Get a Workflow manager object to work with

$wfm = New-object Microsoft.SharePoint.WorkflowServices.WorkflowServicesManager($spSourceweb)

# Get the workflow subscriptions service

$sub = $wfm.GetWorkflowSubscriptionService()

# Get the specific workflow within the list of subscriptions on the specified list

$WF = $sub.EnumerateSubscriptionsByList($spSourcelist.ID) | Where-Object {$_.Name -eq "$TargetWorkflow"}

# Return the Subscription ID

Write-Host $WF.Id

Next is the JavaScript code to trigger the workflow. This method takes a list item ID and a workflow subscription ID as parameters:

function startWorkflow(itemID, subID) {

    // First, ensure the required scripts are loaded (SP.js, SP.WorkflowServices.js)
    SP.SOD.registerSod('SP.ClientContext', SP.Utilities.Utility.getLayoutsPageUrl('sp.js'));
    SP.SOD.registerSod('SP.WorkflowServices.WorkflowServicesManager', SP.Utilities.Utility.getLayoutsPageUrl('SP.WorkflowServices.js'));
    SP.SOD.loadMultiple(['SP.ClientContext', 'SP.WorkflowServices.WorkflowServicesManager'], function () {

        // Set up context for Workflow execution
        var context = SP.ClientContext.get_current();
        var web = context.get_web();
        var wfServiceManager = new SP.WorkflowServices.WorkflowServicesManager(context, web);
        var subscriptionService = wfServiceManager.getWorkflowSubscriptionService();
        var subscription = subscriptionService.getSubscription(subID);
        context.load(subscription, 'PropertyDefinitions');

        // Query to load the workflow to context
        context.executeQueryAsync(
            function (sender, args) {
                console.log("Subscription load success. Attempting to start workflow.");

                // parameters to pass to the workflow. The name must match exactly (optional) 
                var inputParameters = {
                    // the default value is null
                };

                // Query to start the workflow
                wfServiceManager.getWorkflowInstanceService().startWorkflowOnListItem(subscription, itemID, inputParameters);
                context.executeQueryAsync(
                    function (sender, args) {
                        console.log("Successfully started the workflow.");
                    },
                    function (sender, args) {
                        console.error("Failed to start workflow.");
                        console.error("Error: " + args.get_message() + "\n" + args.get_stackTrace());
                    }
                );
            },
            function (sender, args) {
                console.error("Failed to load subscription.");
                console.error("Error: " + args.get_message() + "\n" + args.get_stackTrace());
            }
        );

    });
}

Finally, create a button in the form's HTML that has an onclick listener set to run the above function. Since you don't want to hard-code a list item ID, create the button's onclick listener with jQuery:

<a href="#" onclick="" id="SubmitButton">Submit Form</a>

<script type="text/javascript">
    function onPageLoad() {
        // Get the Item ID from the URL
        var listItemId = GetUrlKeyValue('ID');
        var submitWorkflowId= '8bcb48f2-a5a7-4e38-abfa-3b66384b23ea';

        // add onclick event listener to the submit button
        jQuery('#SubmitButton').on('click', function (ev) {
            ev.preventDefault();
            startWorkflow(listItemId, submitWorkflowId);
            // disable the button after click
            jQuery(this).addClass('disabled');
        });
    }

  // run the above function after the page has loaded completely
  _spBodyOnLoadFunctionNames.push('onPageLoad');
</script>
0

1) Add de Yes/No field to the list

2) Check the value of this field in the first step of the workflow

  • Hi Thank you for your reply. Yes, this button also commits and redirects user. its labelled as 'submit' so i want this action to trigger the workflow as opposed to just saving/creating a new item. thanks. – Angela Northern Apr 5 '16 at 13:12
  • Workflow is on another list? – Juan Pablo Pussacq Laborde Apr 5 '16 at 13:19
  • No, same list. I want the user to feel like they've 'submitted' the form and only once they are ready to does the workflow start. – Angela Northern Apr 5 '16 at 13:22
  • I'm not sure if I understand. The solution I mentioned, save item changes modifying the field value YES / NO. There is a workflow that triggers "on edit item." At that time, if the field is YES, continue with the following steps in the workflow. If it is NO, the workflow ends. This means that in both cases the workflow is triggered, but in one case does nothing. I think it may be a solution without code. Or is there something I did not understand of your requirement? – Juan Pablo Pussacq Laborde Apr 5 '16 at 13:29
  • Ok, I want users to come into the list, complete fields on the 'newform' then save if they wish to return later or submit if they have all the details they require. Only once they are ready to 'submit' should the workflow start. The button i'm using commits and redirects users to 'Thank you' page. I hope this makes it a little clearer. – Angela Northern Apr 5 '16 at 13:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.