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

Notifications

Announcements

No record found.

Community site session details

Community site session details

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

Need help : Javascript

(0) ShareShare
ReportReport
Posted on by 75

Hi guys,

I need some help in this forum, to guide me is there anything wrong within my JavaScript. I got this code from my previous thread whereas I actually didn't have any knowledge of JavaScript. I'm from Dynamics F&O, btw.

So here is the code :

function OpenAndSaveForm(executionContext) {
//Get the form context
var formContext = executionContext.getFormContext();
// Get the form type
var formType = formContext.ui.getFormType();
if(formType == 1) { //create form
    try {
             // for default company
             var globalContext = Xrm.Utility.getGlobalContext();
             var userId = globalContext.userSettings.userId;
             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";
                 formContext.getAttribute("mscrm_company").setValue(companyLookup);
              }
      },
      function(error) {
             console.log(error.message);
       };


       formContext.data.entity.save();
    }
    catch (e) {
        Xrm.Utility.alertDialog(e.message);

    }
  }

}

This is for my model-driven app, What I want to achieve from this code is actually, whenever user click "+ new record", when the form is open, it will automatically save the record.

So I put this into my project as Web Resources and add as OnLoad event in my form. While the saving is working, in that code I also need to set my field "mscrm_company" to user's default company.

I'm not sure why, when this form open, the field company appear in the form with the correct company, but when I hit back, check from he table's raw data, the field is enpty.

May I know is there something wrong with the code? or what is happening ? Is the company displayed on the form actually not save ? or somehow overridden ?

Thanks in advance,

I have the same question (0)
  • MedWong Profile Picture
    75 on at

    Hello again,

    An update, the fact that I forgot Publish is very shameful, but now I have another error saying, Web resource method does not exist, like this :

    pastedimage1630564314076v1.png

    Please help cause I really driving blind with this JavaScript here.

    Thanks

  • Suggested answer
    Pradeep Rai Profile Picture
    5,489 Moderator on at

    Hi MedWong,

    Please correct my understanding.

    1. You want whenever user click "+New Record" then record should get saved automatically with "mscrm_company" field value (i.e. with default value which you are retrieving from WebAPI)

    2. When you run the above script then it is working fine but when you go back and come again then the "mscrm_company" field gets blank.

    If my above understanding is correct then please do below changes:

    After reading code one point i found is you have used the Async call so till the time you get the response from WEBAPI your record is getting saved.
    Because script runs in linear way if it found the async method then it will jump to next line. So, in your case when execution comes to WEBAPI then it calls the webapi and put the calls in stack.

    And execution is moved to next line as a result. Record saved before the WEBAPI respone.

    So, to avoid this.

    Please make below changes:

    function OpenAndSaveForm(executionContext) {
    //Get the form context
    var formContext = executionContext.getFormContext();
    // Get the form type
    var formType = formContext.ui.getFormType();
    if(formType == 1) { //create form
    try {
    // for default company
    var globalContext = Xrm.Utility.getGlobalContext();
    var userId = globalContext.userSettings.userId;
    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";
    formContext.getAttribute("mscrm_company").setValue(companyLookup);
    formContext.data.entity.save();
    }
    },
    function(error) {
    console.log(error.message);
    };



    }
    catch (e) {
    Xrm.Utility.alertDialog(e.message);

    }
    }

    }

    Also, you can use the progress indicator to show processing message:
    Xrm.Utility.showProgressIndicator(message);

    https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/showprogressindicator

    Thanks,
    Pradeep.

    Please mark this as VERIFIED if it helps.

  • Suggested answer
    Pradeep Rai Profile Picture
    5,489 Moderator on at

    Hi,

    Check your entire code there must be some syntax issue like missing of curly braces.

    Thanks,

    Pradeep.

  • MedWong Profile Picture
    75 on at

    Hi Pradeep,

    Thanks you very much for your explanation. Your understanding correctly. 

    So, if my understanding is correct, this line "Xrm.WebApi.online.retrieveRecord("systemuser", userId, "?$expand=cdm_Company($select=cdm_companyid,cdm_name)")" gonna take sometime (async), that is why you put the save "formContext.data.entity.save();"   inside the function if result(success). This is really make sense. Learn a new thing here 

    However, I still now get the error "Web resource method does not exist: OpenAndSaveForm". I wonder why ? Btw I already save and publish the said modification.

    Thanks

  • Suggested answer
    Pradeep Rai Profile Picture
    5,489 Moderator on at

    Hi MedWong,

    Can you please check entire code using VisualCode editor there might be syntax issue.

    Because if we upload any script with syntax error then javascript will not be able to find the required method.

    Please check the entire code some curly braces must be missing.

    Thanks

    Pradeep.

    Please mark this as VERIFIED if it helps.

  • MedWong Profile Picture
    75 on at

    Hi,

    This VisualCode editor is Visual Studio Code, right ?

    I actually never use this, however I just installed it right now, at which part do you suggest I should use to check any syntax error ? or with other word, how am I gonna use this tool ?

    pastedimage1630569496543v1.png

    Thanks in advance.

  • Suggested answer
    Community Member Profile Picture
    on at

    Hi,

    You lose ')' in your code at this line:

    function(error) {
        console.log(error.message);
    });


  • Verified answer
    Pradeep Rai Profile Picture
    5,489 Moderator on at

    Hi MedWong,

    Please check Steve Zhao comment.

    On that point you need to make changes and the modified function will look like below:

    function OpenAndSaveForm(executionContext) {

    //Get the form context

    var formContext = executionContext.getFormContext();

    // Get the form type

    var formType = formContext.ui.getFormType();

    if(formType == 1) { //create form

       try {

                // for default company

                var globalContext = Xrm.Utility.getGlobalContext();

                var userId = globalContext.userSettings.userId;

                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";

                    formContext.getAttribute("mscrm_company").setValue(companyLookup);

                     formContext.data.entity.save();

                 }},

         function(error) {

                console.log(error.message);

          });

       }

       catch (e) {

           Xrm.Utility.alertDialog(e.message);

       }

     }

    }

    You can use above function. Now it is error free.

    Thanks,
    Pradeep

  • MedWong Profile Picture
    75 on at

    Oh my... you both are right and the best !

    How to have those kind of eagle eye 

    I took a break just now because my eyes feel tired already. Is there any tools for this ? or only that Visual Studio Code ? I firstly tried to use this site : https://beautifier.io/

    guess it is not helping.

    Anyway many thanks for your help. it is working now.

  • MedWong Profile Picture
    75 on at

    Probably not much help, but I just found this site : https://jshint.com/

    looks quite ok.

    Anyway thanks again for all helps.

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…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > Customer experience | Sales, Customer Insights, CRM

#1
Tom_Gioielli Profile Picture

Tom_Gioielli 83 Super User 2025 Season 2

#2
Gerardo Rentería García Profile Picture

Gerardo Rentería Ga... 49 Most Valuable Professional

#3
#ManoVerse Profile Picture

#ManoVerse 40

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans