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 :
Microsoft Dynamics CRM (Archived)

Dynamics Online - Initialization problem creating records with javascript

(0) ShareShare
ReportReport
Posted on by

I've written some javascript for custom entities in dynamics online. On a "registration" form, users are presented with questions that must be answered. On save, "answer" records are created and connected to the current "registration." My code that actually creates the record is as follows:

function sendAnswers (parsedAnswer) {
var count = parsedAnswer.length;

//Parse the entity object into JSON
var jsonAnswers = window.JSON.stringify(parsedAnswer);

var serverUrl = Xrm.Page.context.getClientUrl();
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
var odataSetName = "new_regquestionanswers"
var odataUri = serverUrl + ODATA_ENDPOINT + "/" + odataSetName + "Set";

for (var i = 0; i < count; i++) {

    //Parse the entity object into JSON
    var jsonAnswers = window.JSON.stringify(parsedAnswer[i]);
    console.log(jsonAnswers);

    //Asynchronous AJAX function to Create a CRM record using OData
    $.ajax({ type: "POST",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: odataUri,
        data: jsonAnswers,
        beforeSend: function (XMLHttpRequest) {
            //Specifying this header ensures that the results will be returned as JSON.
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
        success: function (data, textStatus, XmlHttpRequest) {
            console.log("The answers successfully posted");
            parent.Xrm.Page.ui.controls.get("new_eventregistrationrelationshipid").setDisabled(true);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("Something went wrong.");
            console.log(XMLHttpRequest.responseText);
        }
    }); 
}

The parameter sent to sendAnswers is read from a hidden field and stored as json.

I'm having an odd issue -- Every time I log into dynamics and try to test this functionality, the very first attempt fails. Subsequent attempts to test succeed and everything works correctly. The error response text I get on the first attempt is:

"Error processing request stream. Error encountered in converting the value from request payload for property 'Id' to type 'Guid', which is the property's expected type. See inner exception for more detail."

I am at a loss of where to go from here. Does anyone have any insight into why this first attempt fails, then everything goes as planned? Thanks for any help.

*This post is locked for comments

I have the same question (0)
  • Suggested answer
    Yadnyesh Kuvalekar Profile Picture
    4,102 on at

    Hi,

    Can you tell on which event the sendAnswers method is called and what parameters are you passing? I believe you are calling this method on save event of registration form.

    Also, try opening existing registration record and check if still your first attempt fails or succeeds?

    I feel, you are trying to call this method on save of record and before registration record gets saved your code tries to bind the answers to registration and hence first time it fails. But when it is saved, then onwards it gets succeeded. So, you can try below method on save event of the record.

    function onSave()
    {
    if (Xrm.Page.ui.getFormType() === 1)
    {
    var iCounter = setInterval(function() {
    if(Xrm.Page.ui.getFormType()!== 1)
    {
    clearInterval(iCounter);
    sendAnswers(parameters);
    }
    },2000);
    }
    else {
    sendAnswers(parameters);
    }
    }
  • fishyjj Profile Picture
    on at

    Thanks for your reply. You are mostly correct, but I already have a function that calls onSave to delay the execution of sendAnswers(). What actually calls onSave is this:

    function waitForSave() {

    var formType = parent.Xrm.Page.ui.getFormType();

    if (formType === 1) {

    setTimeout(getAnswers, 2000);

    }

    else if (formType === 2) {

    setTimeout(getUpdateOrChanged, 1500);

    }

    }

    The function you see here -- getAnswers -- retrieves the data stored in a hidden field on the registration form, and then calls sendAnswers to actually create the records:

    function getAnswers() {

    var guid = Xrm.Page.data.entity.getId();

    var regId = guid.slice(1, -1);

    var jsonAnswer = parent.Xrm.Page.getAttribute("new_hiddenanswers").getValue();

    if (jsonAnswer != null) {

    console.log("first save for this event");

    var parsedAnswer = window.JSON.parse(jsonAnswer);

    var count = parsedAnswer.length;

    for (var i=0; i<count; i++){

    parsedAnswer[i].new_AssociatedRegId = {Id: regId, LogicalName: "new_registration"};

    }

    sendAnswers(parsedAnswer);

    }

    else if (jsonAnswer === null) {

    console.log("no answers");

    return;

    }

    }

    To be clear -- when I say it fails on the first try, I mean only the VERY first try fails. So, I log on, test, and it fails. After that, I can open up a totally new registration and it'll work correctly all the way through. Any ideas?

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 > 🔒一 Microsoft Dynamics CRM (Archived)

#1
SA-08121319-0 Profile Picture

SA-08121319-0 4

#1
Calum MacFarlane Profile Picture

Calum MacFarlane 4

#3
Alex Fun Wei Jie Profile Picture

Alex Fun Wei Jie 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans