Calling a Workflow from a Custom Button

I had a requirement to place a custom button on a layout that needed to call a workflow to accomplish some action.  This can’t be done natively but there is a neat little trick you can employ.

Workflows are triggered when specific field criteria is met.  With this in mind, we need to create a Javascript button that updates a checkbox field on the object.  I created a ‘toggle’ checkbox and set its default to unchecked.

I created a button to execute Javascript.  The code is straightforward: grab the object, check the checkbox, and update the object.  Some error handling will inform the user if the operation was successful or not.

{!REQUIRESCRIPT("/soap/ajax/36.0/connection.js")} 

var myquery = "SELECT Id, Generate_Preview_Toggle__c FROM Special_Waste_Profile__c WHERE Id = '{! Special_Waste_Profile__c.Id}' limit 1"; 

result = sforce.connection.query(myquery); 
records = result.getArray("records"); 

var mySWP = records[0]; 
var updateSWP = new Array(); 

mySWP.Generate_Preview_Toggle__c = true; 
updateSWP.push(mySWP); 

result = sforce.connection.update(updateSWP); 

if(result[0].getBoolean("success")){ 
alert('Check your email, your preview is on its way!'); 
window.location = "/" + "{!Special_Waste_Profile__c.Id}"; 
}else{ 
alert('Contact support. Could not update: '+result); 
}

The next step is to create a workflow rule that acts when my  Generate Preview Toggle field is checked.  The workflow takes care of the task I need to accomplish, and then returns the toggle checkbox to unchecked. This is important, because otherwise the workflow cannot be initiated a second time from the button.

Remember to activate your workflow!

Author: Matt

Matt is a seasoned Salesforce Developer / Architect, with implementations of Sales Cloud, Service Cloud, CPQ, Experience Cloud, and numerous innovative applications built upon the Force.com platform. He started coding in grade 8 and has won awards ranging from international scholarships to internal corporate leadership awards. He is 14x Certified on the platform.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.