Skip to main content

Notifications

Community site session details

Community site session details

Session Id : kg6toDvUOuSz/+k1ngSngr
Power Apps - Building Power Apps
Answered

Model driven apps - web resource JS - cannot read property 0 of null

Like (0) ShareShare
ReportReport
Posted on 7 Feb 2023 03:14:09 by 37

I have a web resource for my model driven app. I have two errors. I'll focus on the first one because I don't expect the second error to be resolved here. I essentially have three lookup fields. The first field has a selection of companies. The second and third fields have filtered selections based on the first field. However, whenever I unselect whatever is in the first field an error occurs and reads "TypeError: Cannot read properties of null (reading '0')".

To make matters worse, the selected options in the second and third fields remain static. I.e. whatever was filtered from my first selection remains in the second and third fields regardless of what I select again in the first column. 

The handler for the first field's event is onChange for "Sdk.attributeOnChange".

 

(My other major problem is that the first field has many duplicate options. There's only supposed to be a unique option for each selection).

 

Any help for pinpointing and resolving the error is greatly appreciated. This is the javascript code for the webresource:

function onlyUnique(value, index, self){
    return self.indexOf(value) == index;
}

var Sdk = window.Sdk || {};
(function () {
    // Define some global variables
    var myUniqueId = "_approvalExpenseVendorForm"; // Define an ID for the notification
    var currentUserName = Xrm.Utility.getGlobalContext().userSettings.userName; // get current user name
    //Retrieves global context to retrieve the client's information (user)
    var message = currentUserName + ": Your JavaScript code in action!";
   
    // Arrays to store individual Approver, MDM and SSCApprover GUIDs from User table
    var arrayOfApprovers = [];
    var arrayOfMDMs = [];
    var arrayOfSSCApprovers = [];


   // Code to run in the form OnLoad event (This does nothing)
    this.formOnLoad = function (executionContext) {

   }
   // Code to run in the attribute OnChange event
   this.attributeOnChange = function (executionContext) {
       
        var formContext = executionContext.getFormContext();


        //Getting current value of company selected to get other values associated with company
        if(formContext.getAttribute("cr866_ab_company")){
        var companyName = []; //added this resolve the error on null properties
        var companyName = formContext.getAttribute("cr866_ab_company").getValue()[0];
       
        //Sets notification saying company is working (may want to review and see if we even want this)
        formContext.ui.setFormNotification("Company=" + companyName.name, "INFO", myUniqueId); //change variable name
        window.setTimeout(function () { formContext.ui.clearFormNotification(myUniqueId); }, 5000);
       
        //Retrieves all instances of the records that have the name of the company selected
        Xrm.WebApi.retrieveMultipleRecords("cr866_ab_company", "?$select=_cr866_approver_value,_cr866_mdm_value,_cr866_sscapprover_value&$filter=cr866_name eq '" + companyName.name + "'").then(
            function success(result) {
               
                // Stores each corresponding approver, MDM or SSC Approver into their appropriate array
                for (var i = 0; i < result.entities.length; i++) {
                    console.log(result.entities[i]); //consider commenting this out
                    //arrayOfApprovers.filter(onlyUnique); <---Do something with this?
                    arrayOfApprovers.push(result.entities[i]._cr866_approver_value);
                    arrayOfMDMs.push(result.entities[i]._cr866_mdm_value);
                    arrayOfSSCApprovers.push(result.entities[i]._cr866_sscapprover_value);                   
                }        
                // Setup listener for when approver is selected to trigger function corresponding to this
                var userControl = formContext.getControl("cr866_approver"); //change var name and code
                userControl.addPreSearch(Sdk.userFilterApprover);        
                // Setup listener for when mdm is selected to trigger function corresponding to this
                userControl = formContext.getControl("cr866_mdm");
                userControl.addPreSearch(Sdk.userFilterMDM);
                // Setup listener for when ssc approver is selected to trigger function corresponding to this
                userControl = formContext.getControl("cr866_sscapproval");
                userControl.addPreSearch(Sdk.userFilterSSC);
            },
            function (error) {
                console.log(error.message);
                // handle error conditions
            }
        );
        }
    }
    // function to handle custom filter for normal approver
    Sdk.userFilterApprover = function () {
        // intitiate filter
        var userFilter = "<filter type='or'>"
        // saw an issue where reusing original array was causing 'undefined' attribute this also only allows unique values
        var arrayOfApprovers1 = arrayOfApprovers.filter(onlyUnique);
        // this checks for any null values and eliminates them
        arrayOfApprovers1 = arrayOfApprovers1.filter(n => n);
       
        // loop through each guid and develop filter around it
        for (var i = 0; i < arrayOfApprovers1.length; i++) {
                    userFilter = userFilter + "<condition attribute='systemuserid' operator='eq' value='" + arrayOfApprovers1[i] + "'/>";
        }
       
        // close filter via syntax
        var userFilter = userFilter + "</filter>"
        // initialize formContext
         var formContext = Xrm.Page.getControl("cr866_ab_company").formContext; //change xrm.Page?
        // adding custom filter
       
        formContext.getControl("cr866_approver").addCustomFilter(userFilter);
   
    }

    // function to handle custom filter for MDM
    Sdk.userFilterMDM = function () {

        // intitiate filter
        var userFilter = "<filter type='or'>"
       
        // saw an issue where reusing original array was causing 'undefined' attribute this also only allows unique values
        var arrayOfMDMs1 = arrayOfMDMs.filter(onlyUnique);
       
        // this checks for any null values and eliminates them
        arrayOfMDMs1 = arrayOfMDMs1.filter(n => n);
       
        // loop through each guid and develop filter around it
        for (var i = 0; i < arrayOfMDMs1.length; i++) {
                    userFilter = userFilter + "<condition attribute='systemuserid' operator='eq' value='" + arrayOfMDMs1[i] + "'/>";
        }
       
        // close filter via syntax
        var userFilter = userFilter + "</filter>"
       
        // initialize formContext
        var formContext = Xrm.Page.getControl("cr866_ab_company").formContext;
        // adding custom filter
        formContext.getControl("cr866_mdm").addCustomFilter(userFilter);      
    }
    // function to handle custom filter for SSC Approver
    Sdk.userFilterSSC = function () {
       
        // intitiate filter
        var userFilter = "<filter type='or'>"
       
        // saw an issue where reusing original array was causing 'undefined' attribute this also only allows unique values
        var arrayOfSSCApprovers1 = arrayOfSSCApprovers.filter(onlyUnique);
       
        // this checks for any null values and eliminates them
        arrayOfSSCApprovers1 = arrayOfSSCApprovers1.filter(n => n);
       
        // loop through each guid and develop filter around it
        for (var i = 0; i < arrayOfSSCApprovers1.length; i++) {
                    userFilter = userFilter + "<condition attribute='systemuserid' operator='eq' value='" + arrayOfSSCApprovers1[i] + "'/>";
        }
        // close filter via syntax
        var userFilter = userFilter + "</filter>"
        // initialize form context
        var formContext = Xrm.Page.getControl("cr866_ab_company").formContext;
        // adding custom filter
        formContext.getControl("cr866_sscapproval").addCustomFilter(userFilter);      
    }
   // Code to run in the form OnSave event
    this.formOnSave = function () {
        console.log('Saving');
   }
}).call(Sdk);
Categories:
  • bfujioka Profile Picture
    37 on 08 Feb 2023 at 22:26:46
    Re: Model driven apps - web resource JS - cannot read property 0 of null

    How would I go about attaching a custom view that would filter out the duplicates?

     

    For clarity, the reason why there are duplicates is because each duplicate row contains the associated value for the approvers.

  • Ethan_009 Profile Picture
    4,838 Super User 2025 Season 1 on 07 Feb 2023 at 06:07:54
    Re: Model driven apps - web resource JS - cannot read property 0 of null

    Just to add up @bfujioka ,

     

    Why do you have duplicates in first lookup?
    Since it will pick the records you enter in table 'Company'. 
    You must check if you're allowing duplicates in your system. 

    Add duplicate detection rules or create and attach a custom view with your requirements

     

    Moveover, disable recent searches from lookup control properties on the form.

     

    Hope this helps

  • Verified answer
    Ethan_009 Profile Picture
    4,838 Super User 2025 Season 1 on 07 Feb 2023 at 06:02:05
    Re: Model driven apps - web resource JS - cannot read property 0 of null

    Hi @bfujioka ,

     

    I'll provide a rough idea of how to validate items and clear accordingly based on input

    var NameSpace = 
    {
     //OnChange of the first Field
     Companies: function(executionContext)
     {
     var formContext = executionContext.getFormContext();
     if(formContext != null || formContext != undefined)
     {
     if(formContext.getAttribute("cr866_ab_company"))
     {
     if(formContext.getAttribute("cr866_ab_company") !== null)
     {
     var company = formContext.getAttribute("cr866_ab_company").getValue();
     if(company == null)
     {
     NameSpace.ClearFields(formContext, ["cr866_secondField", "cr866_thirdField"]);
     }
     else
     {
     NameSpace.SetCustomFiltersByCompany(formContext, company);
     }
     }
     }
     }
     },
     ClearFields: function(formContext, ArrayFields)
     {
     //Use a Loop to clear out the field data from the Form.
     },
     SetCustomFiltersByCompany(formContext, company)
     {
     //Set 2nd and 3rd Fields as per 1st Field company
     }
    }

     

    Here, use NameSpace.Companies() for OnLoad and OnChange of 1st field

     

    Hope this helps

  • Fubar Profile Picture
    7,854 Super User 2025 Season 1 on 07 Feb 2023 at 05:18:18
    Re: Model driven apps - web resource JS - cannot read property 0 of null

     formContext.getAttribute("cr866_ab_company").getValue()[0];

    you need to check if the .getValue() returns null before trying to access its [0]

     

    Edit: also if you clear a Lookup and there are other related Lookups, you will also need to clear them in your code.

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

Understanding Microsoft Agents - Introductory Session

Confused about how agents work across the Microsoft ecosystem? Register today!

Warren Belz – Community Spotlight

We are honored to recognize Warren Belz as our May 2025 Community…

Congratulations to the April Top 10 Community Stars!

Thanks for all your good work in the Community!

Leaderboard > Power Apps - Building Power Apps

#1
MS.Ragavendar Profile Picture

MS.Ragavendar 27

#2
mmbr1606 Profile Picture

mmbr1606 14 Super User 2025 Season 1

#3
EE-04041031-0 Profile Picture

EE-04041031-0 11

Overall leaderboard
Loading started