Calling a Workflow from a Custom Button

Matt/ July 11, 2016/ Salesforce

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.


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; 

result = sforce.connection.update(updateSWP); 

alert('Check your email, your preview is on its way!'); 
window.location = "/" + "{!Special_Waste_Profile__c.Id}"; 
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!

Share this Post

About 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 platform. He started coding in grade 8 and has won awards ranging from international scholarships to internal corporate leadership awards. He is 37x Certified on the platform, including Platform Developer II, B2B Solution Architect and B2C Solution Architect.