This guide shows how to use JavaScript to query Dataverse environment variables and reference the values within a Model Driven App.
This guide assumes you already know how to add JavaScript as a web resource and attach it to a Model-Driven App form. If not, I would review Microsoft’s guides here:
- Create or edit model-driven app web resources to extend an app
- View and edit web resource properties for model-driven app forms
Display Text Environment Value in a Notification Banner
In the first example, we’ll use the formContext.ui.setFormNotification API to display an email address directly on the form. Within my solution, I have the environment variable name “HR Email” with it’s current value as “hr@contoso.com”. When the interview outcome is “Not Successful,” display a notification with the contact email for the user.
The key piece to fetching the value in JavaScript is to use the Xrm.WebApi.retrieveMultipleRecords API to filter on the Environment Variable Value table on our specific Environment Variable by it’s schema name. Dataverse’s Environment Variable Value table is where you can view both a variable’s schema name and value.

We pass the Schema Name to our JavaScript code. The first result of this will contain the record’s value. With the value retrieved, call the Form Notification API.
function getEnvironmentVariableValue(executionContext) {
var formContext = executionContext.getFormContext();
var interviewNotSuccessfulValue = 614250001; // This is the choice value for 'Not successful' in my Candidate Interview Table
var envSchemaNameColumn = "bb89_HREmail"; // ensure this is the schema name of your environment variable
var interviewOutcome = formContext.getAttribute("bb89_interviewoutcome").getInitialValue();
console.log(interviewOutcome);
if (interviewOutcome !== interviewNotSuccessfulValue) {
return;
}
Xrm.WebApi.retrieveMultipleRecords(
"environmentvariablevalue",
`?$select=value&$expand=EnvironmentVariableDefinitionId&$filter=EnvironmentVariableDefinitionId/schemaname eq '${envSchemaNameColumn}'`
).then(
function success(result) {
if (!result.entities || result.entities.length === 0) {
console.warn(`No environment variable found for schema name: ${envSchemaNameColumn}`);
return;
}
var envValue = result.entities[0].value;
console.log("Environment Variable Value:", envValue);
var messageText = `The interview outcome was not successful. Contact ${envValue} for further assistance.`;
formContext.ui.setFormNotification(messageText, "INFO", "_messageId");
},
function (error) {
Xrm.Navigation.openErrorDialog({
details: error.message,
message: "A problem occurred while retrieving an Environment Variable value. Please contact support."
});
}
);
}

Fetch a Boolean Environment Variable Value
I often use an isProduction boolean variable to indicate whether the solution runs in production or a non-production environment. Building on the previous example, we can also fetch this value. To make the script more dynamic and reusable, I take it one step further: instead of hard-coding the schema name in the script, I pass it as a string parameter into the main function.

// Based on the Environment Schema Name column passed into the script, fetch the boolean value result and display a message notification
function determineIsProd(executionContext, envSchemaNameColumn) {
var formContext = executionContext.getFormContext();
Xrm.WebApi.retrieveMultipleRecords(
"environmentvariablevalue",
`?$select=value&$expand=EnvironmentVariableDefinitionId&$filter=EnvironmentVariableDefinitionId/schemaname eq '${envSchemaNameColumn}'`
).then(
function success(result) {
if (!result.entities || result.entities.length === 0) {
console.warn(`No environment variable found for schema name: ${envSchemaNameColumn}`);
return;
}
var isProduction = result.entities[0].value === 'yes'
console.log("Is Production:", isProduction);
if(isProduction === false){
var messageText = `This environment is a non-production environment.`;
formContext.ui.setFormNotification(messageText, "WARNING", "_messageId");
}
},
function (error) {
Xrm.Navigation.openErrorDialog({
details: error.message,
message: "A problem occurred while retrieving an Environment Variable value. Please contact support."
});
}
);
}

Use an Environment Variable to Call a Power Automate from a Command Bar Button
When you import your solution into a new environment, any flows using the trigger “When a HTTP request is received” will create new trigger URLs. By storing the URL in an environment variable, you can dynamically reference it in JavaScript without editing your code for each environment. Instead, you just need to update the environment variable value.
Create the Power Automate
I want to trigger an e-mail to HR through the modern command button to call a Power Automate using it’s HTTP POST URL in an environment variable. In addition, I am going to pass certain parameters for this process like the user who triggered the flow and as the record’s unique identifier.

{
"type": "object",
"properties": {
"username": {
"type": "string"
},
"systemUserId": {
"type": "string"
},
"recordId": {
"type": "string"
}
}
}
For simplicity, the trigger for the Power Automate is “anyone” meaning no authentication is required. Be careful, as anyone who knows the URL could trigger it!

Copying the Flow URL, I added it to my text Environment Variable current value:

Add the JavaScript code and Connect to Command Bar Button
Here’s the hard part: the JavaScript code itself. To make this work, specify your environment variable’s Schema Name (as shown earlier) and build a JSON body that matches the parameters expected by your Power Automate flow. In addition, this code will show a progress indicator while the flow is running. It responds back with a dialog back once the flow response action is called. This may or may not be ideal depending on your use-case if it’s a long-running process.
function triggerHTTPFlow(formContext) {
var recordId = formContext.data.entity.getId().replace("{", "").replace("}", "");
console.log("Record Id:", recordId);
var systemUser = Xrm.Utility.getGlobalContext().userSettings;
var systemUserId = systemUser.userId.replace("{", "").replace("}", "");
var systemUserName = systemUser.userName;
console.log("SystemUser Id:", systemUserId, "User Name:", systemUserName);
var envSchemaNameColumn = 'bb89_EmailHRFlowURL';
// Step 1: Ask for confirmation
var confirmStrings = {
title: "Send Email",
text: "Are you sure you want to email HR?",
confirmButtonLabel: "Yes",
cancelButtonLabel: "No"
};
var confirmOptions = { height: 200, width: 450 };
Xrm.Navigation.openConfirmDialog(confirmStrings, confirmOptions).then(function (dialogResult) {
if (dialogResult.confirmed) {
// Step 2: Only continue if user clicked "Yes"
Xrm.WebApi.retrieveMultipleRecords(
"environmentvariablevalue",
`?$select=value&$expand=EnvironmentVariableDefinitionId&$filter=EnvironmentVariableDefinitionId/schemaname eq '${envSchemaNameColumn}'`
).then(
function success(results) {
if (!results.entities || results.entities.length === 0) {
console.warn(`No environment variable found for schema name: ${envSchemaNameColumn}`);
return;
}
var flowURL = results.entities[0].value;
if (!flowURL) {
console.warn(`No value set for environment variable: ${envSchemaNameColumn}`);
return;
}
console.log("Flow URL:", flowURL);
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
username: systemUserName,
systemUserId: systemUserId,
recordId: recordId
});
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw
};
console.log("Calling flow now...");
fetch(flowURL, requestOptions)
.then(response => response.text())
.then(result => {
console.log("Flow response:", result);
var alertStrings = {
confirmButtonLabel: "OK",
text: "The message has been sent",
title: "Process Complete"
};
var alertOptions = { height: 120, width: 260 };
return Xrm.Navigation.openAlertDialog(alertStrings, alertOptions);
})
.catch(error => console.error("Error calling flow:", error));
},
function (error) {
console.error("Error retrieving environment variable:", error.message);
Xrm.Navigation.openErrorDialog({
details: error.message,
message: "A problem occurred while retrieving an Environment Variable value. Please contact support."
});
}
);
} else {
console.log("User cancelled the flow trigger.");
}
});
}
Almost there! Within the Model Driven App editor, edit your command bar for the table in question (Candidates Application table in my case). Then, create a custom button and link it to your JavaScript web resource.

The end result: JavaScript prompts the user to confirm send, calls the Power Automate Trigger and returns a response!

