Search code examples
javascriptdynamics-crm

Error creating a record XrmServiceToolkit.Rest.Create


I am trying to create an annotation using js: XrmServiceToolkit.Rest.Create.

I get a systax error all the time but I cannot find the problem...

here is my code

var id = parent.Xrm.Page.data.entity.getId().replace('{', '').replace('}', '');
        var nam = parent.Xrm.Page.data.entity.getEntityName();

        var entity = {};

        entity.subject = "title";
        entity.notetext = "description";
        entity.objectid = {
            id: id,
            logicalname: nam
        };



        XrmServiceToolkit.Rest.Create(
        entity,
        "annotation",
        function (result) {
            alert("OK");
        },
        function (error) {
            //Xrm.Utility.alertDialog(error.message, null);
            alert("KO: " + error.message);
        },
        false
        );

I get a "Syntax error" anyone knows where is the problem??

thanks a lot


Solution

  • why don't you use Webapi, if you are on crm 2016 or higer version better go with Webapi. Below is code snippet for webapi which creates noted.

    var entity = {};
    entity.subject = "Test from webapi";
    entity.notetext = "just add some text";
    
    var req = new XMLHttpRequest();
    req.open("POST", Xrm.Page.context.getClientUrl() + "/api/data/v9.1/annotations", false);
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.onreadystatechange = function() {
        if (this.readyState === 4) {
            req.onreadystatechange = null;
            if (this.status === 204) {
                var uri = this.getResponseHeader("OData-EntityId");
                var regExp = /\(([^)]+)\)/;
                var matches = regExp.exec(uri);
                var newEntityId = matches[1];
            } else {
                Xrm.Utility.alertDialog(this.statusText);
            }
        }
    };
    req.send(JSON.stringify(entity));
    

    And now with XrmserviceToolkit

    var entity = {};
    entity.Subject = "Test from webapi 1234";
    entity.NoteText = "just add some text 1234";
    
    XrmServiceToolkit.Rest.Create(entity, "AnnotationSet", function(result) {
        var newEntityId = result.AnnotationId;
    }, function(error) {
        Xrm.Utility.alertDialog(error.message);
    }, false);
    

    Also what is the issue with your code? If you look my code above for XrmserviceToolkit, You need to give Entity name as AnnotationSet. Also you do not need Id because CRM will create Id once a record is created.