Getting Dynamics 365 formContext from Ribbon Workbench

Alfwyn Jordan, 02 October 2019

When calling functions in your custom JavaScript file, you often need to know the context in which the Client API is interacting with your CRM. Previously Xrm.Page was used to represent a form or an item on the form. But now we have switched to using the formContext object. This we can usually get on a form using the following code:

MAG.displayName = function (executionContext) 
{ 
var formContext = executionContext.getFormContext(); // get formContext 

var firstName = formContext.getAttribute("firstname").getValue();  
var lastName = formContext.getAttribute("lastname").getValue(); 
console.log(firstName + " " + lastName); 
} 

Remembering of course that we need to select the “Pass execution context as first parameter” option in the Handler Properties dialogue when defining our event handlers on the form.

That’s easy enough, but how do we pass the execution context when we are modifying a button in Ribbon Workbench and want custom JavaScript to function correctly?

When we select Customise Command in Ribbon Workbench we can pass Execution Parameters.

I’ve chosen to modify the Command for this custom Name button:

Now after selecting the Add Parameter, we select CRM Parameter:

And then select Primary Control:

Now you can get formContext from this parameter as easily as if it were the executionContext.

If you are calling this for a button on the Home or SubGrid ribbons, then your code will look like this:

MAG.displayName = function (primaryControl) 
{ 
var formContext = primaryControl.getFormContext(); // get formContext 

var firstName = formContext.getAttribute("firstname").getValue();  
var lastName = formContext.getAttribute("lastname").getValue(); 
console.log(firstName + " " + lastName); 
}

And if you are calling this for a button on the Form ribbon, you can use primaryControl as if it were the formContext:

MAG.displayName = function (primaryControl) 
{ 
var formContext = primaryControl; // rename as formContext 

var firstName = formContext.getAttribute("firstname").getValue();  
var lastName = formContext.getAttribute("lastname").getValue(); 
console.log(firstName + " " + lastName); 
}