Deploy SharePoint workflows to SharePoint List/Library using JSOM

     Below code will deploy the workflow into SharePoint list/library. We need to use workflow definition id to deploy the workflow.

     First function will get the workflow definition id based on the given workflow name & we will pass the workflow definition id to 2nd function to deploy into list/library. (Note this will return only 2013 workflows)

//add the following workflowservices js files in document.ready function(as mentioned below) Or you can mentioned in your HTML file also.

$(document).ready(function()
{
//load workflow js files
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function(){
SP.SOD.registerSod('sp.workflowservices.js', SP.Utilities.Utility.getLayoutsPageUrl('sp.workflowservices.js'));
SP.SOD.executeFunc('sp.workflowservices.js', "SP.WorkflowServices.WorkflowServicesManager");
});
});


//give your existing workflow name, list/library name, new name for workflow

var existingWorkflowName="SharePoint Designer Custom Workflow Name";
var newDisplayNameForWorkflow = "This name will be displayed for the workflow after deployed. (We can give any name here)"
var listName = "Our SharePoint List/Library Name where to deploy workflow"
var historyListName = 'Workflow History'; //SP workflow history list name
var taskListName= 'Tasks'; //SP workflow task list name

//below function will get workflow definition ID (call below function in your button click event)

function getWorkflowDefIDandDeploy(existingWorkflowName,newDisplayNameForWorkflow)
{
// Getting client context and loading the current web
    var context = SP.ClientContext.get_current();
    var web = context.get_web();
    context.load(web);

    // Workflow Services API entry point - WorkflowServiceManager object
    var servicesManager = SP.WorkflowServices.WorkflowServicesManager.newObject(context, web);
    context.load(servicesManager);

    var workflowDefinitions = servicesManager.getWorkflowDeploymentService().enumerateDefinitions(false);
    context.load(workflowDefinitions);

    context.executeQueryAsync(function (sender, args) {
 
        // enumerateDefinition returns ClientCollection object
        var definitionsEnum = workflowDefinitions.getEnumerator();
        var empty = true;
     
        // Going through the definitions
        while (definitionsEnum.moveNext()) {
            var def = definitionsEnum.get_current();
            console.log(def.get_displayName() + " (id: " + def.get_id() + ")");
            if(def.get_displayName() == existingWorkflowName)
            { var workflowDefId=def.get_id(); deployWorkflow(context,web,servicesManager,workflowDefId,newDisplayNameForWorkflow);}
           
            empty = false;
        }

        if (empty) {alert('No 2013 workflows found!'); }

    }, errFunc);


    // Error handling
    function errFunc(sender, args) {
        alert("Error occured! " + args.get_message());
    };
}


//below function will deploy the workflow to list/library

function deployWorkflow(context,web,servicesManager,workflowDefId,newDisplayNameForWorkflow)
{
//target library where we deploy the workflow
var targetList = web.get_lists().getByTitle(listName);
    context.load(targetList, 'Id');
    // Workflow History list
    var historyList = web.get_lists().getByTitle(historyListName);
    context.load(historyList, 'Id');
    // Workflow Tasks list
    var tasksList = web.get_lists().getByTitle(taskListName);
    context.load(tasksList, 'Id');

    context.executeQueryAsync(function (sender, args) {

        // Creating the subscription
        var sub = new SP.WorkflowServices.WorkflowSubscription(context);

        sub.set_name(newDisplayNameForWorkflow);
        sub.set_enabled(true);
        sub.set_definitionId(workflowDefId);
        sub.set_statusFieldName('WF status');
        sub.set_eventSourceId(targetList.get_id());
        sub.set_eventTypes(["WorkflowStart"]);
        //sub.set_eventTypes(["WorkflowStart","ItemAdded","ItemUpdated"]);

        // These 3 are MANDATORY! Otherwise the workflow will fail to complete
        sub.setProperty("TaskListId", tasksList.get_id().toString());
        sub.setProperty("HistoryListId", historyList.get_id().toString());
        sub.setProperty("FormData", "");

        // Associate the workflow with the list
        servicesManager.getWorkflowSubscriptionService().publishSubscriptionForList(sub, targetList.get_id());

        context.executeQueryAsync(function (sender, args)
        {alert('Workflows added successfully!');        
        }, errFunc);

    }, errFunc);
 
 
// Error handling
function errFunc(sender, args) {
   alert("Error occured! " + args.get_message());
};

}

Comments

Popular posts from this blog

Upload Single/Multiple file by using the REST API and jQuery SharePoint 2013

A type named 'SP.Data. could not be resolved by the model error

Add content type to SharePoint List/Library using REST API