Business Process Flows (BPF) in Dynamics 365 offer a structured way to guide users through a defined process. However, there are scenarios where progression to the next stage must be validated against specific business rules. In this blog, we see how to implement custom validations on stage progression using JavaScript.
Let us take a simple scenario where a Lead can only progress to the next stage of a BPF if
Lead Quality = Hot and Lead Source = Web
If these conditions are not met, users will receive a notification, and the stage change will be prevented.
Below is the sample code
function OnLoad(executionContext)
{
var formContext = executionContext.getFormContext();
formContext.data.process.addOnPreStageChange(validateStageProgression);
}
function validateStageProgression(executionContext)
{
var bpfSampleStage = "6e2b5d9e-da30-4a47-8ca9-d75c24fd51f4";
var formContext = executionContext.getFormContext();
var rating = formContext.getControl('header_process_leadqualitycode').getAttribute().getValue();
var leadSource = formContext.getControl('header_process_leadsourcecode').getAttribute().getValue();
var stageObj = formContext.data.process.getActiveStage();
var stageId = stageObj.getId();
var requiredFieldErrorId = "contractValidationNotificationId";
formContext.ui.clearFormNotification(requiredFieldErrorId);
if(stageId)
{
if (stageId.toLowerCase() === bpfSampleStage)
{
if (executionContext.getEventArgs().getDirection() === "Next")
{
executionContext.getEventArgs().preventDefault();
if(rating == 1 && leadSource == 8) // rating = Hot and Source = Web
{
formContext.data.process.removeOnPreStageChange(validateStageProgression);
formContext.data.process.moveNext();
}
else
{
notificationMessage = "Cannot move to the next stage until conditions are met !";
formContext.ui.setFormNotification(notificationMessage, "ERROR", requiredFieldErrorId)
}
}
}
}
}
The addOnPreStageChange method registers the validation function on the form’s load event to monitor stage changes.
The preventDefault() method stops the stage transition if the conditions are not met, ensuring data integrity.
If the validation fails, an error notification is displayed using the setFormNotification() method, guiding users to correct the data.
Upon satisfying the conditions, moveNext() is invoked programmatically to move the process to the next stage.
As shown below, clicking on Next as rating and lead source values do not satisfy the condition, we can see the notification on the form and the user is not able to move to the next stage.

Hope it helps..
Discover more from Nishant Rana's Weblog
Subscribe to get the latest posts sent to your email.

2 thoughts on “Customizing Business Process Flows: Stage Validation Using JavaScript (Dynamics 365 / Dataverse)”