Switch business process programmatically in Dynamics CRM based on business logic during create of a record.

Confused by the title? Well let me explain here the exact requirement that I had recently for one of my customers.

For the opportunity entity we designed multiple business process flows. However the condition was whenever a user tries to create a new opportunity, first a default business process flow would load. Depending on the data entered by the user, based on business logic as soon the record saves, the record should switch to the appropriate business process flow.

So it’s pretty obvious how we would do it.

  • On the save of the form, we would check for the data entered by the user and determine the business process.
  • Then we set the business process id and the stage id appropriately
  • After the record is saved successfully we refresh the entire form, so that the appropriate process loads.

 

Simple isn’t it. But there are two triggers we need to handle here.

  • Pre-Save of the record – To determine the business process to be set for the record.
  • Post-save of the record – To reload the form.

For the first point, we can easily register a function on the save of the form. However if you do that there is one catch to it. The OOB save button click is synchronous and you cannot register any event handlers on successful completion of the save.

So we need to approach this approach differently. Off-course there must be many other good ways to achieve this, but the following is way how I approached the same and it worked great.

  • Create a button with the same look and feel as the Save button. You can easily do that with the help of Ribbon Workbench Editor
  • Create visibility rules so that OOB Save is hidden during the create mode and the custom Save button is visible.
  • Register a function on the click of the custom ‘Save’ button.
  • Determine the processid the stageid as per the data entered by the user.
  • Set the processid and the stageid using Xrm.Page.getAttribute(“processid”).setValue(processid) and Xrm.Page.getAttribute(“stageid’).setValue(stageid).
  • Now the next trick would be using the method – Xrm.Page.data.save.then(successCallback, errorCallback);
  • successCallback – The method to call after the save is called.
  • errorCallback – The method to call if the save fails.
  • In the successCallback method write the code to refresh the form.
    • Xrm.Utility.openEntityForm(“<entitylogicalname>”, Xrm.Page.data.entity.getId());

So the form would be refreshed and the appropriate business process and stage would be loaded.

Hope this helps!