Retrieving environment variable value in Javascript
The script below might help if you wanted to read CDS environment variable value in your javascript web resource.
top.environmentVariables = [];
function getEnvironmentVariableInternal(varName){
"use strict";
top.environmentVariables[varName] = null;
Xrm.WebApi.retrieveMultipleRecords("environmentvariabledefinition", `?$top=1&fetchXml=<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'>
<entity name='environmentvariabledefinition'>
<attribute name='defaultvalue' />
<filter type='and'>
<condition attribute='schemaname' operator='eq' value='` + varName + `' />
</filter>
<link-entity name='environmentvariablevalue' from='environmentvariabledefinitionid' to='environmentvariabledefinitionid' link-type='outer' alias='varvalue'>
<attribute name='value' />
</link-entity>
</entity>
</fetch>`).then(
function success(result) {
for (var i = 0; i < result.entities.length; i++) {
if(typeof(result.entities[i]["varvalue.value"]) != "undefined")
{
top.environmentVariables[varName] = result.entities[i]["varvalue.value"];
}
else if(typeof(result.entities[i].defaultvalue) != "undefined")
{
top.environmentVariables[varName] = result.entities[i].defaultvalue;
}
else{
top.environmentVariables[varName] = null;
}
}
},
function (error) {
console.log(error.message);
}
);
}
function getEnvironmentVariable(executionContext)
{
"use strict";
getEnvironmentVariableInternal("SCHEMA_NAME_OF_YOUR_VARIABLE");
}
Just a couple of notes:
1. I’m using WebAPI + FetchXML to get the values
This is because I need to query the definition (where the default value is), but I want to bring in environment-specific value in the same request. I can’t use “expand” with Web API when starting from the variable definition, since the lookup is from the value to the definition (not the other way around). And I can’t start with the “value” in my query, since the value might not exist in the environment (but the definition does exist)
2. I’m storing variable value (default or overridden) in the top.environmentVariables array
This way, I can access that array from the script associated to a ribbon button (which is a completely separate script)
This was originally posted here.

Like
Report
*This post is locked for comments