Создание инцидента с использованием Xrm.WebApi.createRecord завершится неудачно, если вы сначала не сделаете alert () - PullRequest
0 голосов
/ 14 июня 2019

У меня есть небольшой метод, который создает запись об инциденте, используя Xrm.WebApi.createRecord

function createChangeRequest(emailData) {
var createRequestObj = null;

try {
    //create CR object
    createRequestObj = new Object();
    createRequestObj.title = emailData.name;
    createRequestObj.description = emailData.description;

    var senderId = emailData.senderId.replace('{', '').replace('}', '');
    var account = "";

    if (emailData.senderEntity == 'contact') {
        try {
            //alert(senderId);
            Xrm.WebApi.retrieveRecord("contact", senderId, "$select=fullname&$expand=parentcustomerid_account($select=accountid,name)")
                .then(function (data) {
                    if (data.parentcustomerid_account.accountid != null) {
                        //alert(data.parentcustomerid_account.accountid);
                        account = data.parentcustomerid_account.accountid;

                        //set the lookup value
                        createRequestObj["customerid_account@odata.bind"] = "/accounts(" + account.toUpperCase() + ")";
                    }
                },
                    function (error) {
                        Xrm.Utility.alertDialog(error.message);
                    });
        } catch (e) {
            Xrm.Utility.alertDialog(e.message);
        }

        //set the lookup value
        createRequestObj["primarycontactid@odata.bind"] = "/contacts(" + senderId + ")";
    }
    else if (emailData.senderEntity == 'account') {
        //set the lookup value
        createRequestObj["customerid_account@odata.bind"] = "/accounts(" + senderId + ")";
    }

alert('wibble');

    Xrm.WebApi.createRecord("incident", createRequestObj).then(function (result) {           
        //get the guid of created record
        var recordId = result.id;

        //below code is used to open the created record
        var windowOptions = {
            openInNewWindow: false
        };
        //check if XRM.Utility is not null
        if (Xrm.Utility != null) {
            //open the entity record
            Xrm.Utility.openEntityForm("incident", recordId, null, windowOptions);
        }
    },
    function (error) {
        Xrm.Utility.alertDialog('Create error - ' + error.message);
    });
}
catch (e) {
    Xrm.Utility.alertDialog('General Error - ' + e.message);
}
}

Это работает, как и ожидалось, однако, если я удаляю или закомментирую alert('wibble');, оно следует за обратным вызовом ошибки и выдает сообщение «Создать ошибку - произошла непредвиденная ошибка»

Я не знаю, почему это так, или не вижу причины, по которой короткая задержка, вызванная нажатием кнопки «ОК», должна заставить его работать.

1 Ответ

0 голосов
/ 14 июня 2019

Это может быть из-за асинхронного поведения Xrm.WebApi методов.Объект обещания, возвращаемый этим вызовом, должен запускаться в браузере по своему усмотрению:)

Переместить строку Xrm.WebApi.createRecord в успешном обратном вызове Xrm.WebApi.retrieveRecord, как показано ниже:

Xrm.WebApi.retrieveRecord("contact", senderId, "$select=fullname&$expand=parentcustomerid_account($select=accountid,name)")
            .then(function (data) {
                if (data.parentcustomerid_account.accountid != null) {
                    //alert(data.parentcustomerid_account.accountid);
                    account = data.parentcustomerid_account.accountid;

                    //set the lookup value
                    createRequestObj["customerid_account@odata.bind"] = "/accounts(" + account.toUpperCase() + ")";

                    Xrm.WebApi.createRecord("incident", createRequestObj).then(function (result) {           
                        //get the guid of created record
                        var recordId = result.id;

                       //below code is used to open the created record
                       var windowOptions = {
                           openInNewWindow: false
                       };
                       //check if XRM.Utility is not null
                       if (Xrm.Utility != null) {
                           //open the entity record
                           Xrm.Utility.openEntityForm("incident", recordId, null, windowOptions);
                       }
                   },
                   function (error) {
                       Xrm.Utility.alertDialog('Create error - ' + error.message);
                   });

                 }
                },
                function (error) {
                    Xrm.Utility.alertDialog(error.message);
                });
...