web
You’re offline. This is a read only version of the page.
close
Skip to main content
Community site session details

Community site session details

Session Id :
Customer experience | Sales, Customer Insights,...
Answered

Javascript : variable undefined

(0) ShareShare
ReportReport
Posted on by 75

Hello guys,

Need your help to lead me what's wrong with my JavaScript code. Forgive me because I have no experience in JavaScript, I only get this from the web with addition of my needed.

function CreateRecord() {

var globalContext = Xrm.Utility.getGlobalContext();
var userId = globalContext.userSettings.userId;
var today = new Date();

try {
var entityName = "xyz_orders"; //Entity Logical Name

//Default company
Xrm.WebApi.online.retrieveRecord("systemuser", userId, "?$expand=cdm_Company($select=cdm_companyid,cdm_name)").then(
function success(result) {
if (result.hasOwnProperty("cdm_Company")) {
var cdm_Company_cdm_companyid = result["cdm_Company"]["cdm_companyid"];
var cdm_Company_cdm_name = result["cdm_Company"]["cdm_name"];
var companyLookup = new Array();
companyLookup[0] = new Object();
companyLookup[0].id = cdm_Company_cdm_companyid;
companyLookup[0].name = cdm_Company_cdm_name;
companyLookup[0].entityType = "cdm_company";
var companycode = companyLookup;
}
},
function(error) {
console.log(error.message);
}
);


//Data used to Create record
var data = {
"xyz_description": "New order",
"xyz_company": companycode,
"xyz_date": today
};
Xrm.WebApi.createRecord(entityName, data).then(
function success(result) {
Xrm.Utility.alertDialog("Success");
},
function (error) {
Xrm.Utility.alertDialog("Error creating header");
}
);
}
catch (e) {
Xrm.Utility.alertDialog(e.message);
}
}

The error is actually what I highlighted in red, companycode. It seems when it is run, it is said company code is not defined. I thought to defined variable is only adding "var" in front of it ?

Your kind help is appreciated.

Thanks

I have the same question (0)
  • MedWong Profile Picture
    75 on at
    RE: Javascript : variable undefined

    Hi,

    I think the "companycode is not defined" error is because the 1st paragraph when retrieve record is error, is that correct ? so it not fall into those script with companycode variable defined ?

    The idea of the RetrievedRecord function is to get user's default company, and I want to put it in some variable first. Then, on below it (2nd paragraph) is insert a record into my table with those data in "data" array with one of them is the default company variable.

    Please help, as I actually coming from D365 F&O and has no knowledge of this JavaScript. Happened to use this because now we have Dual-Write which force me to sometime take a look on CRM side

    Thanks

  • Suggested answer
    Pradeep Rai Profile Picture
    5,489 Moderator on at
    RE: Javascript : variable undefined

    Hi,

    The main cause of getting undefined is Async behaviour of code.

    Please check below code. In below part i have moved the create record code in success callback of  systemuser record

    function CreateRecord() {
    
        var globalContext = Xrm.Utility.getGlobalContext();
        var userId = globalContext.userSettings.userId;
        var today = new Date();
    
        try {
            var entityName = "xyz_orders"; //Entity Logical Name
    
            //Default company
            Xrm.WebApi.online.retrieveRecord("systemuser", userId, "?$expand=cdm_Company($select=cdm_companyid,cdm_name)").then(
                function success(result) {
                    if (result.hasOwnProperty("cdm_Company")) {
                        var cdm_Company_cdm_companyid = result["cdm_Company"]["cdm_companyid"];
                        var cdm_Company_cdm_name = result["cdm_Company"]["cdm_name"];
                        var companyLookup = new Array();
                        companyLookup[0] = new Object();
                        companyLookup[0].id = cdm_Company_cdm_companyid;
                        companyLookup[0].name = cdm_Company_cdm_name;
                        companyLookup[0].entityType = "cdm_company";
                        var companycode = companyLookup;
    
                        //Data used to Create record
                        var data = {
                            "xyz_description": "New order",
                            "xyz_company": companycode,
                            "xyz_date": today
                        };
                        Xrm.WebApi.createRecord(entityName, data).then(
                            function success(result) {
                                Xrm.Utility.alertDialog("Success");
                            },
                            function (error) {
                                Xrm.Utility.alertDialog("Error creating header");
                            }
                        );
                    }
                },
                function (error) {
                    console.log(error.message);
                }
            );
    
    
    
        }
        catch (e) {
            Xrm.Utility.alertDialog(e.message);
        }
    }
    

    Thanks,
    Pradeep.

    Please mark this as VERIFIED it helps

  • Suggested answer
    Pradeep Rai Profile Picture
    5,489 Moderator on at
    RE: Javascript : variable undefined

    Hi,

    Once correction in above code. While creating record please replace below code with red code:

    "xyz_company": companycode,

    pastedimage1632885125619v1.png

    Replace with it below code

    "schenmaNameofCompanyLookup@odata.bind": "/pluralentitynameofcdm_company(" + cdm_Company_cdm_companyid+")",

    Thanks,

    Pradeep.

  • MedWong Profile Picture
    75 on at
    RE: Javascript : variable undefined

    Hi Pradeep,

    So actually it is not how it is defined, but the Async behavior.

    Thank you very much on your help. The variable undefined is disappeared now, but I guess it is falls into error while "createRecord" as currently the error is my custom message "Error creating header"

    Mind to guide me how to know what is wrong and how can I resolved this ?

    Thanks

  • Pradeep Rai Profile Picture
    5,489 Moderator on at
    RE: Javascript : variable undefined

    If possible can you please share the update code to create record. would be helpful if you attach the error snap.

    also, we need to follow below code to set lookup values during record creation:

    "schemaNameofCompanyLookup@odata.bind": "/pluralentitynameofcdm_company(" + cdm_Company_cdm_companyid+")",

    We need to change the above red part with actual values

    Thanks,

    Pradeep.

  • MedWong Profile Picture
    75 on at
    RE: Javascript : variable undefined

    Hi Pradeep,

    I'm sorry, but what is schemaNameOfCompanyLookup ? also the pluralentitynameofcdm_company ?

    For the error snap, is exactly the custom message only, like this ->

    pastedimage1632890281070v1.png

    So it is pop up after click Save button.

    Thanks

  • Suggested answer
    Pradeep Rai Profile Picture
    5,489 Moderator on at
    RE: Javascript : variable undefined

    //Data used to Create record
    var data = {
    "xyz_description": "New order",
    "xyz_company": companycode,
    "xyz_date": today
    };
    Xrm.WebApi.createRecord(entityName, data).then(
    function success(result) {
    Xrm.Utility.alertDialog("Success");
    },
    function (error) {
    Xrm.Utility.alertDialog("Error creating header");
    }
    );

    In above code, the "xyz_company" is of lookup type and to set lookup value during creation of record we need to follow below syntax:

    "schemaNameofLookup@odata.bind"="/pluralentityName(GUID)";

    To get shemaname we need to go to field customization and there we will find schema name column as shown below:

    pastedimage1632891494244v1.png


    And to get puralname of entity then open Xrmtoolbox and serach metadata browser then select entity and get value from entitysetname column as shown below:

    pastedimage1632891701602v3.png

    Now, once we have both then during record i will write code in below way:
    new_funds@odata.bind="/fundses(recordGUID)";

    So, In your code check the schema and entity plural name.

    Hope this helps.

    Thanks,
    Pradeep.

    Please mark this as VERIFIED. if it helps.

  • MedWong Profile Picture
    75 on at
    RE: Javascript : variable undefined

    Hi,

    I'm sorry, for SchemaName, now I have located it and know exactly what I supposed to use. However for Xrmtoolbox, this is something new to me. I just download it, but may advice which tool I should install ? Because it look like I didn't have Xrmtoolbox for Microsoft Dataverse and Dynamics 365

    .pastedimage1632901018200v1.png

    Thanks,

  • Pradeep Rai Profile Picture
    5,489 Moderator on at
    RE: Javascript : variable undefined

    Hi,


    Please search as shown in below screen:

    pastedimage1632901484216v1.png

    After this you need connect to CRM.

    Thanks,
    Pradeep.

  • MedWong Profile Picture
    75 on at
    RE: Javascript : variable undefined

    Hi,

    Thank you for your quick response. Found it.

    Here is my finding :

    Schema name : jm_company

    pastedimage1632901992106v1.png

    ---> This is from my entity's field which is the target of created record.

    pluralentityname : cdm_companies

    pastedimage1632902215744v2.png

    ---> This is the table cdm_company 

    So with that information, whether this is correct then ?

    var data = {
    "jm_description": "New order",
    "jm_company@odata.bind":  "/cdm_companies(" + cdm_Company_cdm_companyid+")",
    "jm_date": today
    };

    Thanks

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

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Abhilash Warrier – Community Spotlight

We are honored to recognize Abhilash Warrier as our Community Spotlight honoree for…

Leaderboard > Customer experience | Sales, Customer Insights, CRM

#1
Rishabh Kanaskar Profile Picture

Rishabh Kanaskar 235

#2
MVP-Daniyal Khaleel Profile Picture

MVP-Daniyal Khaleel 177

#3
Tom_Gioielli Profile Picture

Tom_Gioielli 156 Super User 2025 Season 2

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans