How to use Xrm and formContext in HTML WebResource in Dynamics 365 CRM

By | August 5, 2020

Introduction

In this blog we will explore how to pass ‘Xrm’ and ‘formContext’ in HTML pages using the
‘getContentWindow’ client API in Unified Interface of Dynamics 365 CRM so that we can get or set the form attributes inside the HTML web resource.  As we all know, parent.Xrm is going to deprecate in near future so below is the supported way to use the ‘Xrm’ and ‘formContext’ in HTML page.

Suppose there is a HTML web resource on Account entity form which shows notes record related to a Parent Account. And from the HTML page we need to read or set some fields on Account record using formContext and also want to do CRUD operations inside the HTML Page using Xrm.webapi. So, the Xrm and formContext won’t be accessed directly in HTML page. To access, you can follow the below steps:

1. Add the below code in the ‘onLoad’ event handler of Account entity. The below code is written in Typescript so you need to compile it in JavaScript and add it on ‘onLoad’ event of the account form.

onLoad(executionContext:any): void {

try {

//validate execution context

if (executionContext != undefined )

{

//get form context

let formContext = executionContext.getFormContext();

//validate form context

if (formContext != undefined ) {

//Get AccountNotes control

let accountNotesControl = formContext.getControl(“WebResource_AccountNotes”);

//Validate control

if (accountNotesControl != null && accountNotesControl != undefined) {

//get getContentWindow

accountNotesControl.getContentWindow().then(

function (contentWindow) {

//Pass xrm and formcontext

contentWindow.setClientApiContext(Xrm,formContext);

}

)

}

}

else{

//Show alert

Xrm.Navigation.openAlertDialog({ title: “Error”, text: “formContext is undefined” });

} }

else{

//Show alert

Xrm.Navigation.openAlertDialog({ title: “Error”, text: “executionContext is undefined” });

}

}

catch (ex) {

//Show alert

Xrm.Navigation.openAlertDialog({ title: “Error”, text: ex.message });

}

}

In the above code, we are accessing the HTML page using getControl method. Using the getContentWindow() which returns a content window instance representing an IFRAME or web resource we are going to pass the parameter ‘Xrm’ and ‘formContext’ in HTML page.

‘WebResource_AccountNotes’ is the name of the HTML web resource control added on the Account form.

HTML WebResource in Dynamics 365 CRM

2. Bind the above code on ‘Onload’ of the Account form as shown in below screenshot:

HTML WebResource in Dynamics 365 CRM

3. Now, add the following code in your HTML web resource:

<script>

function setClientApiContext(xrm, formContext) {

//To set the attribute on Account form

formContext.getAttribute(“preferredcontactmethodcode”).setValue(1);

//To do CRUD operation

var data =

{

“subject”: “Sample”,

}

// create Note record

xrm.WebApi.createRecord(“annotation”, data).then(

function success(result) {

console.log(“Notes created with ID: ” + result.id);

},

function (error) {

console.log(error.message);

// handle error conditions

}

);

}

</script>

You can see in above function we have set the value of the ‘preferredcontactmethodcode’ attribute on Account record and we created a new note record using Xrm.webapi functions.

Note:

1. The above blog will only work on Unified Interface.

2. The function name defined in the HTML page i.e. ‘setClientApiContext’ should use the same function name while calling in Onload function of Form event handler.

Conclusion

As illustrated above, you can now pass ‘Xrm’ and ‘formContext’ in HTML pages using the
‘getContentWindow’ client API in Unified Interface of Dynamics 365 CRM.

Marketing4Dynamics – Mailchimp and Dynamics 365 CRM integration to plan effective sales strategies, increase sales and improve ROI

  • Sync Audiences, Members and Tags from Mailchimp to CRM
  • Sync CRM Marketing List (Contacts/Leads) to Mailchimp
  • Sync Campaigns and Member activities from Mailchimp to CRM
  • Monitor and analyze Mailchimp campaign statistics through Dashboards in CRM

6 thoughts on “How to use Xrm and formContext in HTML WebResource in Dynamics 365 CRM

  1. Vamsi

    Hi

    I have tried the same way , but its not hitting the function in HTML webresoure?

    function LoadFormcontext_Verifyasset(executionContext) {
    var wrName = “WebResource_verifyasset”;
    var formContext = executionContext.getFormContext();
    var wrControl = formContext.getControl(wrName);
    if (wrControl) {
    wrControl.getContentWindow().then(
    function (contentWindow) {
    console.log(formContext);
    contentWindow.setClientApiContext(xrm, formContext);
    }
    );
    }
    }

    IN HTML with in the script tag

    function setClientApiContext(xrm, formContext) {
    alert(formContext.getAttribute(“gts_mode”).getValue());
    }

    Am I missing any thing here?
    Thanks
    Vamsi

    1. Inogic

      The code looks good. Verify whether the web resource name (WebResource_verifyasset) is correct or not and also verify whether you have enabled execution context parameter in ‘OnLoad’ event handler or not. You can see highlighted part in below screenshot:

      HTML Webresource

      Could you also let us know what issues are you exactly facing by looking into the console? It would be helpful for us to resolve your issue.

      Thanks!

  2. qwe

    //validate execution context
    if (executionContext != null && executionContext != undefined && executionContext != “undefined” && executionContext != “null” && executionContext != “”)

    This “validation” check clutters the code and causes problems by hiding bugs.

    If you’ve ticked “Pass execution context as first parameter” when setting up the event handler (as you should when setting up _any_ event handlers from now on, when Unified Interface is the only option), then the parameter will be a valid execution context object at runtime, and the check is unneeded. The subsequent similar check against formContext is also unneeded – if you have an execution context object, it can give you a form context.

    If you haven’t ticked this, then the parameter will be undefined. In this case, you _want_ your code to fail loudly (because you’ve forgotten to tick the box) when in fact the check just silently bypasses the (usually mandatory) logic you wanted.

    The checks also add extra indentation and branching to the function, making it harder to follow than it needs to be, particularly if the function is longer and contains more such logic.

    Additionally, none of the values being validated can _ever_ take on the string values “null”, “undefined” or “”, so these conditions will never be satisfied and are just adding extra clutter.

    1. Inogic

      Hi,

      Thanks for the suggestion. We have updated the blog accordingly. Now we have only checked executionContext as undefined to simplify the code.

  3. Manoj

    why every has given the same example where they are calling the html on load only n using the context… what if I want to call it on button click on html … all bloggers has done copy past the same thing…..

    1. Inogic

      Hi Manoj,

      Even if you want to perform the functionality on button click of the HTML, you need to pass the Xrm and Formcontext from the onLoad event of the form using getContentWindow().

      The getContentWindow() returns the content window that represents an IFRAME or web resource. In the HTML, you need to declare the global variable which you can use to perform operations on the click of the button.

      You can refer to the below link:
      https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/getcontentwindow

      Hope this helps,
      Thanks!

Comments are closed.