Skip to main content

Notifications

Community site session details

Community site session details

Session Id :
Dynamics 365 general forum

Account on form Onload_UCI error

(0) ShareShare
ReportReport
Posted on by 1,023

Hi,

I have the below code on Account form load. When the genearl user is  accesing account form, he is getting error and system admin doesnot get any error. Please advise how  what changes in the code needs to be done to stop error in UCI? webclient doesnt get this error.

Error message - Cannot read property 'getFormContext'

function showHideTabsByRole_OnLoad(executionContext) {
//Retrieve Server URL
var globalContext = Xrm.Utility.getGlobalContext();
var serverUrl = globalContext.getClientUrl();

var str = "";

// Cater for URL differences between on premise and online
if (serverUrl.match(/\/$/)) {
serverUrl = serverUrl.substring(0, serverUrl.length - 1);
}

//Check for security role
var currentUserRoles = globalContext.userSettings.securityRoles;

for (var i = 0; i < currentUserRoles.length; i++) {

var userRoleId = currentUserRoles[i];

//Detail for entity & Web API query
var entity = "Role";

var filterQuery = "/XRMServices/2011/OrganizationData.svc/RoleSet?$select=Name&$filter=RoleId eq guid'" + userRoleId + "'";

var query = serverUrl + filterQuery;

var service = new XMLHttpRequest();
service.open("GET", query, false);
service.setRequestHeader("X-Requested-Width", "XMLHttpRequest");
service.setRequestHeader("Accept", "application/json,text/javascript, */*");
service.send();

if (service.readyState == 4 /* complete */) {
if (service.status == 200) {
if (JSON.parse(service.response).d.results[0] != null && JSON.parse(service.response).d.results[0].Name != "") {
str += JSON.parse(service.response).d.results[0].Name + ",";
}
}
}
}

GetEntityData(str.substring(0, str.length - 1), executionContext);
}

  • yify Profile Picture
    1,023 on at
    RE: Account on form Onload_UCI error

    Thank you so much. Really Appreciate your help! Your suggestion did solve my problem!!!!

    Thanks Again!

  • yify Profile Picture
    1,023 on at
    RE: Account on form Onload_UCI error

    Ravi, Thanks for the response. 

    Please bear with me. I am not a developer. If I just remove the red highlighted, will that be fine?

    Thanks!

    Appreciate all your help!

  • Verified answer
    RaviKashyap Profile Picture
    55,410 Moderator on at
    RE: Account on form Onload_UCI error

    Hi,

    The error is occurring on method  ShowOrHideListOfViews which excepts a third paramter called "executionContext". Now you are calling this method from GetEntityData method but while calling you are not passing the execution context. This is why when within the ShowOrHideListOfViews you are doing executionContxt.getFormContext, it is throing this error as it cannot find executionContext.

    So to fix this, you need to change the GetEntityData method i.e. while calling the ShowOrHideListOfViews, you need to pass execution context as the third parameter.

    ===========

    function GetEntityData(retrieveReq, executionContext) {
        var userRoleName = retrieveReq.split(",");
        var formContext = executionContext.getFormContext();
        var formTypeValue = formContext.ui.getFormType();

        var viewsToVisibleByAdmin = ["tab_6", "tab_10", "tab_radocuments", "tab_11", "tab_15", "tab_12", "tab_14", "tab_9"];


        for (var i = 0; i < userRoleName.length; i++) {

            var usersCurrentRole = userRoleName[i].toLowerCase();

            if (usersCurrentRole == DistributorGeneralUser_ROLENAME) {
                //Disable fields

                if (formTypeValue == 1 || formTypeValue == 2) {
                    ShowOrHideListOfViews(viewsToVisibleByAdmin, false, executionContext);
                }

                return;
            }

        }
    }

    ==================

    The reason it is working fine in classic is because classic interface stores the context on a global level so this can be used without passing it manualy whereas UCI doesn't.

    Hope this helps.

    PS: please add a a tag #AskRavi in your response form me to get a direct notification

  • yify Profile Picture
    1,023 on at
    RE: Account on form Onload_UCI error

    Please find below log file and error image

    pastedimage1566862895716v1.png

    TypeError: Unable to get property 'getFormContext' of undefined or null reference
    at ShowOrHideListOfViews (crm.crm.dynamics.com/.../prm_Account:326:5)
    at GetEntityData (crm.crm.dynamics.com/.../prm_Account:350:17)
    at showHideTabsByRole_OnLoad (crm.crm.dynamics.com/.../prm_Account:322:5)
    at np.prototype.executeFunction (crm.crm.dynamics.com/.../app.js
    at np.prototype.execute (crm.crm.dynamics.com/.../app.js
    at Yd.prototype._executeIndividualEvent (crm.crm.dynamics.com/.../app.js
    at Yd.prototype._executeEventHandler (crm.crm.dynamics.com/.../app.js
    at execute (crm.crm.dynamics.com/.../app.js
    at O.prototype._executeSyncAction (crm.crm.dynamics.com/.../app.js
    at O.prototype._executeSync (crm.crm.dynamics.com/.../app.js

  • RaviKashyap Profile Picture
    55,410 Moderator on at
    RE: Account on form Onload_UCI error

    Hi James,

    Can you also share a screenshot of the error/ log file? Generaly in the error it is also mentioned that which method is throwing the error. The script you have shared uses multiple methods so unsure where exactly it can throw that error.

    And is this happened on load of the form or some other event?

  • yify Profile Picture
    1,023 on at
    RE: Account on form Onload_UCI error

    Ravi, This is all the JS code we have on the Account form

    /// <reference path="common.js" />
    // JavaScript source code
    var saved = false;
    var isOnload = false;

    function onload(executionContext) {
    var formName = null;
    debugger;
    var formContext = executionContext.getFormContext();
    if (formContext.getAttribute("prm_consultingindustry") != null) {
    formContext.getAttribute("prm_consultingindustry").setRequiredLevel("none");
    formContext.ui.controls.get("prm_consultingindustry").setDisabled(true);
    }


    if (formContext.ui.formSelector.getCurrentItem() != null) {
    formName = formContext.ui.formSelector.getCurrentItem().getLabel();
    }
    if (formName != null && formName == "Commercial Administration") {
    if (formContext.getAttribute("prm_consultingindustry") != null) {
    formContext.getAttribute("prm_consultingindustry").setRequiredLevel("none");
    formContext.ui.controls.get("prm_consultingindustry").setDisabled(false);
    }
    }
    // Signature (Common.js) - FilterNotNull(filterOn, primaryAttribute)
    if (formName != null && formName != "Distributor Form" && formName != "Distributor Restricted Form" && formName != "Distributor General Form") {
    var Sdk = window.Sdk || {};
    Sdk.filterCustomerAccounts = function () {
    var customerAccountFilter = "<filter type='and'> <filter type='and'> <condition attribute='statecode' operator='eq' value='0' /> <condition attribute='prm_sapbpid' operator='not-null' /> <filter type='or'> <condition attribute='prm_locationid1' operator='eq' uiname='ACP ThinManager' uitype='account' value='" + formContext.data.entity.getId() + "' /> <condition attribute='prm_locationid1' operator='null' /> </filter> </filter> </filter>";
    formContext.getControl("prm_bpid").addCustomFilter(customerAccountFilter, "prm_location");
    }
    Sdk.setParentAccountIdFilter = function () {
    formContext.getControl("prm_bpid").addPreSearch(Sdk.filterCustomerAccounts);
    }

    Sdk.setParentAccountIdFilter();
    //FilterLookupAddConditions("prm_bpid", "<filter type='and'> <filter type='and'> <condition attribute='statecode' operator='eq' value='0' /> <condition attribute='prm_sapbpid' operator='not-null' /> <filter type='or'> <condition attribute='prm_locationid1' operator='eq' uiname='ACP ThinManager' uitype='account' value='" + formContext.data.entity.getId() + "' /> <condition attribute='prm_locationid1' operator='null' /> </filter> </filter> </filter>");
    }

    if (formName != null && (formName == "Commercial Sponsoring" || formName == "Commercial Form" || formName == "Commercial Administration")) {
    if (formContext.getAttribute("prm_bpid") != null) {
    //formContext.getControl("prm_bpid").setFocus();
    }
    }

    isOnload = true;
    BPID_OnChange(executionContext,isOnload);
    ProgramType_OnLoad(executionContext);

    preFilterLookup("prm_consultingindustry", "prm_consultingindustry", "1", null, executionContext);
    var arraySubgrids = new Array("PartnerApprovers_contextualButtonsContainer");
    ToggleDisplay(arraySubgrids, "none", true, executionContext);


    // Pre Filter Headquarter Locations
    var currentAccount = formContext.data.entity.getId();
    if (currentAccount != null) {
    preFilterLookup("prm_americahq", "prm_locationid1", currentAccount, "location", executionContext);
    preFilterLookup("prm_asiahq", "prm_locationid1", currentAccount, "location", executionContext);
    preFilterLookup("prm_europehq", "prm_locationid1", currentAccount, "location", executionContext);
    preFilterLookup("prm_globalhq", "prm_locationid1", currentAccount, "location", executionContext);
    } else {
    formContext.ui.controls.get("prm_americahq").setDisabled(true);
    formContext.ui.controls.get("prm_asiahq").setDisabled(true);
    formContext.ui.controls.get("prm_europehq").setDisabled(true);
    formContext.ui.controls.get("prm_globalhq").setDisabled(true);
    }

    if (formContext.getAttribute("prm_applicationstatus") != null) {
    if (formContext.getAttribute("prm_applicationstatus").getValue() != null) {
    var applicationStatus = formContext.getAttribute("prm_applicationstatus").getValue();
    var partnerStatus = null;
    if (formContext.getAttribute("statuscode") != null) {
    partnerStatus = formContext.getAttribute("statuscode").getValue();
    if (partnerStatus != null && applicationStatus == 166130002 && partnerStatus == 100000002) {
    if (formName != null && formName == "Commercial Form") {
    formContext.data.entity.attributes.forEach(function (attribute, index) {
    var control = formContext.getControl(attribute.getName());
    if (control) {
    control.setDisabled(true)
    }
    });
    return;
    }
    }
    }
    }
    }

    if (formContext.ui.getFormType() == 1) { // Create Form
    formContext.getAttribute("new_motionanalyzer").setValue("No");
    var globalContext = Xrm.Utility.getGlobalContext();
    var setUservalue = new Array();
    setUservalue[0] = new Object();
    setUservalue[0].id = globalContext.userSettings.userId;
    setUservalue[0].entityType = 'systemuser';
    if (formContext.getAttribute("prm_rockwellsponsor") != null) {
    formContext.getAttribute("prm_rockwellsponsor").setValue(setUservalue);
    formContext.getAttribute("prm_rockwellsponsor").setSubmitMode("always");
    }
    }
    }

    function controlFormRibbon(executionContext) {
    var formContext = executionContext.getFormContext();
    var formName = null;
    if (formContext.ui.formSelector.getCurrentItem() != null) {
    formName = formContext.ui.formSelector.getCurrentItem().getLabel();
    }

    if (formName != null && formName == "Commercial Form") {
    return true;
    }
    else {
    return false;
    }
    }

    function SetSPANumber(executionContext) {
    var formContext = executionContext.getFormContext();
    var programType = formContext.getAttribute("prm_programtype").getValue();
    var country = formContext.getAttribute("prm_country").getValue();
    var spaNumber = formContext.ui.controls.get("prm_spanumber");

    if (programType != null && country != null && spaNumber != null) {
    var programTypeid = programType[0].id;
    var countryid = country[0].id;
    var spaNumberResults = RetrieveMultiple("prm_spanumberSet?$select=prm_spanumber,prm_spanumberId&$filter=prm_ProgramTypeId/Id eq guid'" + programTypeid + "' and prm_CountryId/Id eq guid'" + countryid + "'");
    if (spaNumberResults != null && spaNumberResults.results.length > 0 && spaNumberResults.results[0] != null) {

    formContext.getAttribute("prm_spanumber").setValue([{ id: spaNumberResults.results[0].prm_spanumberId, name: spaNumberResults.results[0].prm_spanumber, entityType: "prm_spanumber" }]);

    }

    }

    }
    function OnChangeOfPrimaryLocation(executionContext) {
    debugger;
    var formContext = executionContext.getFormContext();
    var location = null;
    if (formContext.getAttribute("prm_bpid") != null) {
    location = formContext.getAttribute("prm_bpid").getValue();
    }
    if (location != null) {
    var locationid = location[0].id;

    var locationResults = RetrieveMultiple("prm_locationSet(guid'" + locationid + "')?$select=prm_LocationName,prm_CustomerType,prm_APRBase");
    var programType = formContext.getAttribute("prm_programtype").getValue();
    if (locationResults != null && locationResults.prm_CustomerType != null && programType == null) {
    var programTypeResults = RetrieveMultiple("new_programtypeSet?$select=new_name,new_programtypeId&$filter=prm_CustomerType/Value eq " + locationResults.prm_CustomerType.Value);

    if (programTypeResults != null && programTypeResults.results.length > 0 && programTypeResults.results[0].new_programtypeId != null && programTypeResults.results[0].new_name != null) {
    var lookupData = new Array();
    var lookupItem = new Object();
    //Set the GUID
    lookupItem.id = programTypeResults.results[0].new_programtypeId;
    // Set the name
    lookupItem.name = programTypeResults.results[0].new_name;
    lookupItem.entityType = "new_programtype";
    lookupData[0] = lookupItem;
    formContext.getAttribute("prm_programtype").setValue(lookupData);
    ProgramType_OnChange(executionContext);

    if (lookupItem.name == "Consultant") {
    if (formContext.getAttribute("prm_consultingindustry") != null) {
    formContext.getAttribute("prm_consultingindustry").setRequiredLevel("required");
    formContext.getAttribute("prm_consultingindustry").setValue(null);
    formContext.ui.controls.get("prm_consultingindustry").setDisabled(false);
    }
    }
    }
    }

    if (locationResults != null && locationResults.prm_LocationName != null) {
    if (formContext.getAttribute("name") != null) {
    formContext.getAttribute("name").setValue(locationResults.prm_LocationName);
    }
    if (formContext.getAttribute("prm_displayname") != null) {
    formContext.getAttribute("prm_displayname").setValue(locationResults.prm_LocationName);
    }
    }

    if (locationResults != null && locationResults.prm_APRBase != null && locationResults.prm_APRBase.Id != null) {
    var lookupData = new Array();
    var lookupItem = new Object();
    //Set the GUID
    lookupItem.id = locationResults.prm_APRBase.Id;
    //Set the name
    lookupItem.name = locationResults.prm_APRBase.Name;
    lookupItem.entityType = locationResults.prm_APRBase.LogicalName;
    lookupData[0] = lookupItem;
    if (formContext.getAttribute("prm_aprbase") != null) {
    formContext.getAttribute("prm_aprbase").setValue(lookupData);
    formContext.getAttribute("prm_aprbase").setSubmitMode("always");
    }
    }
    }
    }

    function BPID_OnChange(executionContext,isOnload) {
    var formContext = executionContext.getFormContext();
    var bpidObject = null;
    if (formContext.getAttribute("prm_bpid") != null) {
    bpidObject = formContext.getAttribute("prm_bpid").getValue();
    }
    var filterAlreadyApplied = false;
    var fieldsArray = new Array("address1_composite", "prm_displayname", "address1_line1", "address1_line2", "address1_line3", "address1_city", "prm_country", "prm_stateprovince", "address1_postalcode", "emailaddress1", "address1_telephone1", "fax", "websiteurl", "prm_programtype"); // "prm_distributorcontact");
    if (bpidObject != null) {
    ToggleFieldsAll(fieldsArray, true, executionContext);
    }

    fieldsArray = new Array("primarycontactid", "prm_softwarelibrarian", "prm_encompasscontentadmin", "prm_executivecontact", "prm_momcontact", "prm_applicant");
    if (formContext.ui.getFormType() == 1) {
    ToggleFieldsAll(fieldsArray, true, executionContext);
    }
    else {
    ToggleFieldsAll(fieldsArray, false, executionContext);
    }

    if (!isOnload)
    OnChangeOfPrimaryLocation(executionContext);
    }

    function OnSave(executionContext) {
    var formContext = executionContext.getFormContext();
    formContext.getAttribute("statuscode").setSubmitMode("always");
    formContext.getAttribute("prm_applicationstatus").setSubmitMode("always");
    }

    function OnStatusChange(executionContext) {
    var formContext = executionContext.getFormContext();
    if (formContext.getAttribute("statuscode") != null && formContext.getAttribute("statuscode").getValue() != null &&
    formContext.getAttribute("prm_applicationstatus") != null && formContext.getAttribute("prm_applicationstatus").getValue() != null &&
    formContext.getAttribute("prm_requirementsmet") != null) {
    var applicationStatus = formContext.getAttribute("prm_applicationstatus").getValue();
    var partnerStatus = formContext.getAttribute("statuscode").getValue();
    if (applicationStatus == 166130002 && partnerStatus == 100000002) { // Partner Approved
    formContext.getAttribute("prm_requirementsmet").setValue(true);
    }
    }
    }

    function ProgramType_OnLoad(executionContext) {
    var formContext = executionContext.getFormContext();
    var programType = formContext.getAttribute("prm_programtype").getValue();
    var ToolkitRequired = formContext.ui.controls.get("prm_istoolkitrequired");

    if (programType != null && ToolkitRequired != null) {
    var programTypeid = programType[0].id;
    var programTypeResults = RetrieveMultiple("new_programtypeSet?$select=prm_AllowEditsonToolkitRequired,prm_NoToolkitRequired,new_programtypeId&$filter=new_programtypeId eq guid'" + programTypeid + "'");
    if (programTypeResults != null && programTypeResults.results.length > 0 && programTypeResults.results[0].prm_AllowEditsonToolkitRequired != null) {
    var allowToolkitEdits = programTypeResults.results[0].prm_AllowEditsonToolkitRequired;
    ToolkitRequired.setDisabled(!allowToolkitEdits);
    }
    }
    }

    function ProgramType_OnChange(executionContext) {
    var formContext = executionContext.getFormContext();
    var programType = formContext.getAttribute("prm_programtype").getValue();
    var ToolkitRequired = formContext.getAttribute("prm_istoolkitrequired");

    if (programType != null && ToolkitRequired != null) {
    var programTypeid = programType[0].id;
    var programTypeResults = RetrieveMultiple("new_programtypeSet?$select=prm_AllowEditsonToolkitRequired,prm_NoToolkitRequired,new_programtypeId&$filter=new_programtypeId eq guid'" + programTypeid + "'");
    if (programTypeResults != null && programTypeResults.results.length > 0 && programTypeResults.results[0].prm_NoToolkitRequired != null) {
    var defaultToolkitRequired = programTypeResults.results[0].prm_NoToolkitRequired;
    ToolkitRequired.setValue(defaultToolkitRequired);
    }
    }
    }

    //var SYSTEM_ADMINISTRATOR_ROLENAME = "system administrator";
    //var SYSTEM_CUSTOMIZER_ROLENAME = "system customizer";
    var DistributorGeneralUser_ROLENAME = "distributor general user";

    function showHideTabsByRole_OnLoad(executionContext) {
    //Retrieve Server URL
    var globalContext = Xrm.Utility.getGlobalContext();
    var serverUrl = globalContext.getClientUrl();

    var str = "";

    // Cater for URL differences between on premise and online
    if (serverUrl.match(/\/$/)) {
    serverUrl = serverUrl.substring(0, serverUrl.length - 1);
    }

    //Check for security role
    var currentUserRoles = globalContext.userSettings.securityRoles;

    for (var i = 0; i < currentUserRoles.length; i++) {

    var userRoleId = currentUserRoles[i];

    //Detail for entity & Web API query
    var entity = "Role";

    var filterQuery = "/XRMServices/2011/OrganizationData.svc/RoleSet?$select=Name&$filter=RoleId eq guid'" + userRoleId + "'";

    var query = serverUrl + filterQuery;

    var service = new XMLHttpRequest();
    service.open("GET", query, false);
    service.setRequestHeader("X-Requested-Width", "XMLHttpRequest");
    service.setRequestHeader("Accept", "application/json,text/javascript, */*");
    service.send();

    if (service.readyState == 4 /* complete */) {
    if (service.status == 200) {
    if (JSON.parse(service.response).d.results[0] != null && JSON.parse(service.response).d.results[0].Name != "") {
    str += JSON.parse(service.response).d.results[0].Name + ",";
    }
    }
    }
    }

    GetEntityData(str.substring(0, str.length - 1), executionContext);
    }

    function ShowOrHideListOfViews(listOfView, ENABLE, executionContext) {
    var formContext = executionContext.getFormContext();
    if (listOfView.length > 0) {
    for (var f = 0; f < listOfView.length; f++) {
    (formContext.ui.tabs.get(listOfView[f]) != null) ? formContext.ui.tabs.get(listOfView[f]).setVisible(ENABLE) : "";
    }
    }
    }

    function GetEntityData(retrieveReq, executionContext) {
    var userRoleName = retrieveReq.split(",");
    var formContext = executionContext.getFormContext();
    var formTypeValue = formContext.ui.getFormType();

    var viewsToVisibleByAdmin = ["tab_6", "tab_10", "tab_radocuments", "tab_11", "tab_15", "tab_12", "tab_14", "tab_9"];


    for (var i = 0; i < userRoleName.length; i++) {

    var usersCurrentRole = userRoleName[i].toLowerCase();

    if (usersCurrentRole == DistributorGeneralUser_ROLENAME) {
    //Disable fields

    if (formTypeValue == 1 || formTypeValue == 2) {
    ShowOrHideListOfViews(viewsToVisibleByAdmin, false);
    }

    return;
    }

    }
    }

    function statusOnChange(executionContext) {

    var formContext = executionContext.getFormContext();
    var Statuscode = formContext.getAttribute("statuscode").getValue();
    var ApplicationStatus = formContext.getAttribute("prm_applicationstatus").getValue();

    var fieldsArray = new Array("primarycontactid", "prm_softwarelibrarian", "prm_encompasscontentadmin", "prm_executivecontact", "prm_momcontact", "prm_applicant");

    if (Statuscode == 100000000 || (Statuscode != 100000000 && ApplicationStatus == null)) {
    ToggleFieldsAll(fieldsArray, true, executionContext);
    }
    else {

    ToggleFieldsAll(fieldsArray, false, executionContext);
    }

    }

  • RaviKashyap Profile Picture
    55,410 Moderator on at
    RE: Account on form Onload_UCI error

    Hi,

    Are you sure you are getting " Cannot read property 'getFormContext'", asking becuse the script you have shared doesn't use getFormXontext anywhere. It could be in the GetEntityData may be?

    Please share your complete script.

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

November Spotlight Star - Khushbu Rajvi

Congratulations to a top community star!

Forum Structure Changes Coming on 11/8!

In our never-ending quest to help the Dynamics 365 Community members get answers faster …

Dynamics 365 Community Platform update – Oct 28

Welcome to the next edition of the Community Platform Update. This is a status …

Leaderboard > Dynamics 365 general forum

Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans