Skip to main content

Notifications

Microsoft Dynamics CRM (Archived)

Setting Customer on Case from JavaScript

Posted on by 225

Hello, 

I'm trying to implement the following function for Cases/Incidents:

* When you select a Contact [primarycontactid], the Account [customerid] should be automatically set to the Contacts Account [parentcustomerid]

I've created a function to do this, but for some reason it won't let users actually save the record - instead it tells them to fill out customerid. I'm not really sure what the issue is here, any suggestions?

function onChange_ContactId() {
    // set up for async request
    var sourceFieldName = "parentcustomerid";
    var targetFieldName = "customerid";
    var sourceEntityName = "contact";
    var targetEntityName = "account";
    var id = _getId("primarycontactid");
    if (id == null || id == undefined) return; // field was set to null, do nothing

    // build async request
    var request = new XMLHttpRequest();
    var query = "?$select=_"+sourceFieldName+"_value";
    var expansion = "";
    var reqLine = Xrm.Page.context.getClientUrl()+"/api/data/v9.1/"+sourceEntityName+"s("+id.slice(1, -1)+")"+query+expansion; // concatenates request string
    request.open("GET",reqLine, true);
    request.setRequestHeader("OData-MaxVersion","4.0");
    request.setRequestHeader("OData-Version","4.0");
    request.setRequestHeader("Accept","application/json");
    request.setRequestHeader("Content-Type","application/json; charset=utf-8");
    request.setRequestHeader("Prefer", "odata.include-annotations=\"*\""); // adds FormattedValue to the result
    request.onreadystatechange = function () {
        if (this.readyState === 4) { // is ready
            request.onreadystatechange = null;
            if (this.status === 200) { // and successful
                var result = JSON.parse(this.response); // parse JSON response
                if (result["_"+sourceFieldName+"_value"] == null || result["_"+sourceFieldName+"_value"] == "") return; // ensure there's a result
                var reference = [{ // built entityReference from result
                        "entityType":targetEntityName,
                        "id":result["_"+sourceFieldName+"_value"],
                        "name":result["_"+sourceFieldName+"_value@OData.Community.Display.V1.FormattedValue"]
                    },];
                Xrm.Page.getAttribute(targetFieldName).setValue(reference); // apply result to targetFieldName            
            } else {
                alert("attempted to retrieve "+sourceEntityName+"="+id+"\nstatus is "+this.status+"\nresponse is:\n"+this.response);
            }
        }
    }
    request.send(); // send async request
}


*This post is locked for comments

  • Verified answer
    Alex Fun Wei Jie Profile Picture
    Alex Fun Wei Jie 33,626 on at
    RE: Setting Customer on Case from JavaScript

    Hi,

    I tested with your code, I  would consider this is a bug, because I tested with a very simple JS

    EG:

    if i run a simple JS during on load, this works perfectly. But if on change, I hit the same error you faced.

    I created a very simple JS that set this lookup

    0830.19.PNG

    as you can see , i didnt face any error during onload event.

    3187.17.PNG

    now i turn off the onload event and change it to onchange event.

    2022.18.PNG

    I hit the same error you are facing. :(

    0830.19.PNG

    Besides that, I 've tested your code, it works perfectly and I've tested the same scenario in Opportunity, it works perfectly too.

    So I would consider this as a bug. Please contact Microsoft support in this case.

  • Suggested answer
    Sreevalli Profile Picture
    Sreevalli 3,256 on at
    RE: Setting Customer on Case from JavaScript

    Hi,

    If you are able to see the right result in reference variable then use setSubmitMode always

    Xrm.Page.getAttribute(targetFieldName).setSubmitMode("always");

    and how about using quick create form on form to show Contacts ParentCustomer and background workflow (to populate customer from contact) to sync data in DB level. I think it helps in performance improvement on form loading

  • DKasp Profile Picture
    DKasp 225 on at
    RE: Setting Customer on Case from JavaScript

    Still looking for suggestions (or solutions)

  • DKasp Profile Picture
    DKasp 225 on at
    RE: Setting Customer on Case from JavaScript

    Yes, I did output the reference details via an alert:

                   alert(  "entityType="+reference[0].entityType+"\n"+
    
                           "id="+reference[0].id+"\n"+
    
                           "name="+reference[0].name);


    This results in:

    entityType=account
    
    id=GUID-RIGHT-HERE
    
    name=CompanyNameHere


    It does show up in the form, but it's still marked as not filled and when submitting it will tell the user to fill out the Customer field. I can even click on the filled in Customer and it takes me to the correct account record.

  • Alex Fun Wei Jie Profile Picture
    Alex Fun Wei Jie 33,626 on at
    RE: Setting Customer on Case from JavaScript

    Hi,

    did you try to debug? what are the value inside the reference (entityType, id and name) , are they correct?

  • DKasp Profile Picture
    DKasp 225 on at
    RE: Setting Customer on Case from JavaScript

    Since I missed that: _getId() simply retrieves the Id from primarycontactid, as you'd guess by the name of the function.

    function _getId(fieldName) {
        if (Xrm.Page.getControl(fieldName) != null) {
            var lookup = Xrm.Page.getControl(fieldName).getAttribute().getValue(); // retrieves an object array
            if (lookup == null) return lookup;
            return lookup[0].id; // return the Guid from said array
        }
    }

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

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Community AMA December 12th

Join us as we continue to demystify the Dynamics 365 Contact Center

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,253 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,188 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans