JavaScript in Power Platform – Frequently Asked Interview Questions.

Hello Guys,

In our previous blog, we discussed some useful tips to prepare for interviews on Business Rules. Today, we will look at some important JavaScript tips and interview questions related to Dynamics 365 CRM.



Do follow us to know more about Dynamics and Power Platform. Also if you like our blog then please comment and share this blog with your friends.

The client API object model for model driven apps provides you objects and methods that you can use to apply custom business logic in model driven app using JavaScript. These includes:

  • Gets or sets attribute value.
  • Show and hide user interface elements.
  • Reference multiple controls per attribute.
  • Access multiple forms per entity.
  • Manipulate form navigation items.
  • Interact with the business process flow control.


Let's see what questions can be asked by interviewers.

1. How do we start using JavaScript in Dynamics 365 CRM?

The First Step to Use JavaScript in Dynamics 365 CRM (Dataverse)
JavaScript cannot run directly in Dynamics 365 CRM. To use JavaScript, it must first be uploaded as a JavaScript Web Resource.

Step 1: Create a JavaScript File Locally.
example: account_form.js

Step 2: Add your JavaScript code inside the file.
example:

var BLG = {};

BLG.accountOnload = function (executionContext) 
{
    var formContext = executionContext.getFormContext();
    console.log("Form loaded");
};

Step 3: Upload the JS as Web resource
  • Go to Solutions in Dynamics 365
  • Select your solution
  • Add a Web Resource
  • Upload the account_form.js file
  • Save and publish
Step 4: Add the Web Resource to a Form
  • Open the required Form (e.g., Account Main Form)
  • Go to Form Properties
  • Add the JavaScript Web Resource
  • Ensure Enabled for the form is checked
Step 5: Bind JavaScript Functions to Form Events
  • Select the required event (OnLoad, OnSave, OnChange)
  • Choose the function name (e.g., BLG.accountOnload)
  • Check "Pass execution context as first parameter"
2. How to access entity?
var entityName = formContext.data.entity.getEntityName();

3. How to get record id?
var recordId = formContext.data.entity.getId();
recordId = recordId.slice(1, -1);

4. How to read, set and clear the entity fields?
var name = formContext.getAttribute("name").getValue();
formContext.getAttribute("name").setValue("New Account Name");
formContext.getAttribute("name").setValue(null);

5. How to Disable / Enable Field and Hide or Show a Field?
formContext.getControl("name").setDisabled(true); 

formContext.getControl("new_fieldname").setVisible(false);

formContext.getControl("new_fieldname").setVisible(true);

6. How to get and set Lookup Field?
var lookup = formContext.getAttribute("parentaccountid").getValue();
if (lookup !== null) {
    var accountId = lookup[0].id;
    var accountName = lookup[0].name;
}

var lookupValue = {};
lookupValue.id: "GUID-HERE";
lookupValue.name: "Contoso Ltd";
lookupValue.entityType: "account";

7. How can we make a field mandatory or optional?
formContext.getAttribute("telephone1").setRequiredLevel("required");
formContext.getAttribute("telephone1").setRequiredLevel("none");
formContext.getAttribute("telephone1").setRequiredLevel("recommended");

8. How to check form type?
var formType = formContext.ui.getFormType();
1 = Create
2 = Update

9. How can we display an alert message in Dynamics 365 using JavaScript?

var alertStrings = {
    confirmButtonLabel: "OK",
    text: "Record saved successfully!",
    title: "Information"
};

var alertOptions = {
    height: 120,
    width: 260
};

Xrm.Navigation.openAlertDialog(alertStrings, alertOptions);

10. How can we display an error message in Dynamics 365 using JavaScript?

Xrm.Navigation.openErrorDialog({
    message: "An unexpected error occurred while saving the record.",
    details: "Please contact the system administrator."
});

11. How to Add / Remove Option Set Values Dynamically?

formContext.getControl("new_status").removeOption(2);

formContext.getControl("new_status").addOption({
    text: "Pending Approval",
    value: 100000005
});

12. How to access Header/footer fields?
formContext.getControl("header_fieldname");
formContext.getControl("footer_fieldname");
formContext.getAttribute("header_fieldname");
formContext.getAttribute("footer_fieldname");

13. How to access BPF fields?

formContext.getControl("header_process_fieldname");
formContext.getAttribute("header_process_fieldname");

14. How to call action using JS?
In Dynamics 365 (Dataverse), you can call a Custom Action (Process / Action) using JavaScript via the Xrm.WebApi.

Calling an Unbound Action

function callCustomAction(executionContext) {

    var formContext = executionContext.getFormContext();
    var recordId = formContext.data.entity.getId().slice(1, -1);

    var request = {
        entityId: recordId,

        getMetadata: function () {
            return {
                boundParameter: null, // unbound action
                parameterTypes: {
                    "entityId": {
                        typeName: "Edm.String",
                        structuralProperty: 1
                    }
                },
                operationName: "new_MyCustomAction",
                operationType: 0 // Action
            };
        }
    };

    Xrm.WebApi.online.execute(request).then(
        function (response) {
            if (response.ok) {
                Xrm.Navigation.openAlertDialog({
                    text: "Action executed successfully!"
                });
            }
        },
        function (error) {
            Xrm.Navigation.openErrorDialog({
                message: error.message
            });
        }
    );
}

Call a Bound Action (Entity Action)

function callBoundAction(executionContext) {

    var formContext = executionContext.getFormContext();
    var recordId = formContext.data.entity.getId().slice(1, -1);

    var request = {
        entity: {
            id: recordId,
            entityType: "account"
        },

        getMetadata: function () {
            return {
                boundParameter: "entity",
                parameterTypes: {
                    "entity": {
                        typeName: "mscrm.account",
                        structuralProperty: 5
                    }
                },
                operationName: "new_AccountAction",
                operationType: 0
            };
        }
    };

    Xrm.WebApi.online.execute(request);
}


Call Action with Input Parameters

var request = {
    Name: "Test Account",
    Amount: 5000,

    getMetadata: function () {
        return {
            boundParameter: null,
            parameterTypes: {
                "Name": { typeName: "Edm.String", structuralProperty: 1 },
                "Amount": { typeName: "Edm.Decimal", structuralProperty: 1 }
            },
            operationName: "new_CustomActionWithParams",
            operationType: 0
        };
    }
};


15. Is it possible to make Xrm.WebApi calls synchronous in Dynamics 365 CRM?

Web API calls in Dynamics 365 (Dataverse) cannot be made synchronous when using the standard Xrm.WebApi.

All Xrm.WebApi methods like retrieveRecord, createRecord, updateRecord, and execute return a Promise, which is inherently asynchronous.

16. If we want to achieve something synchronous using JS then can we do it?

Yes, we can make HTTP requests using CRM REST Builder, which generates JavaScript code for XMLHttpRequest. In this approach, you can choose whether the request is synchronous or asynchronous.

For example, in XMLHttpRequest, the third parameter of open() controls this:

req.open("GET", url, false);


17. How to call Power Automate Flow using JS?

var req = new XMLHttpRequest();

req.open("POST", Flowurl, true); // async call

req.setRequestHeader("Content-Type", "application/json");


req.onreadystatechange = function () {

    if (req.readyState === 4) {

        if (req.status === 200 || req.status === 202) {

            console.log("Flow executed successfully", req.responseText);

        } else {

            console.error("Flow execution failed", req.statusText);

        }

    }

};


var data = JSON.stringify({ accountId: "00000000-0000-0000-0000-000000000000" });

req.send(data);


18. I have a JavaScript function registered on the OnSave event of a form. However, whenever I create a new record, this function is being triggered unexpectedly. What could be the possible reason?

It’s possible that we are calling a function on the OnLoad event that contains the code formContext.data.entity.save(). Since this programmatically saves the record as soon as the form loads, it triggers the OnSave event, even for new records. That’s why the OnSave function runs unexpectedly. To avoid this, we should either avoid calling save() on load or add proper checks for the form type and save mode so that it doesn’t execute on new records or during autosave.

19. how to skip AutoSave in JS?

function onSaveHandler(executionContext) {

    var saveEvent = executionContext.getEventArgs();

    var saveMode = saveEvent.getSaveMode();

    // Skip AutoSave (saveMode 70 = Save & Close, 58 = AutoSave)

    if (saveMode === 58) return;

    // Your code here

}

20. How do you launch a new record form as a popup dialog in Dynamics 365 using JavaScript?

function openNewAccountForm() {
    var entityFormOptions = {};
    entityFormOptions["entityName"] = "account"; // Logical name of entity
    entityFormOptions["useQuickCreateForm"] = true; // Opens as a popup (Quick Create)
    entityFormOptions["openInNewWindow"] = false; // Keep within the app

    Xrm.Navigation.openForm(entityFormOptions).then(
        function (success) {
            if (success.savedEntityReference) {
                console.log("New record created with ID: " + success.savedEntityReference[0].id);
            }
        },
        function (error) {
            console.error(error.message);
        }
    );
}

You can pre-populate fields in the new record form:

var entityFormOptions = { entityName: "account", useQuickCreateForm: true };
var formParameters = {
    name: "Test Account",
    telephone1: "1234567890"
};

Xrm.Navigation.openForm(entityFormOptions, formParameters);

21. How to update Read Only fields using JS?
By default, D365 saves only dirty (modified) fields on form save.
setSubmitMode() lets you override this behavior.
var attr = formContext.getAttribute("new_total");
attr.setValue(5000);
attr.setSubmitMode("always");

"dirty" (default) - Field is saved only if changed.
"always" - Field is saved every time.
"never" - Field is NOT saved.

22. What is the purpose of updating read only field using JS?
Consider scenarios where workflows, plugins, or Power Automate flows are triggered on the change of a read-only field, we update that field programmatically using JavaScript. By setting the value via JavaScript and using setSubmitMode("always"), we ensure the field value is submitted and saved, which in turn triggers the downstream processes.

Hope It helps...

Comments

Popular posts from this blog

Creating Custom API in D365.

Read Only Sub Grid & Editable Sub grid in Dynamics 365

Using Polymorphic Lookups in D365.