Click here to Skip to main content
15,868,141 members
Articles / Programming Languages / Javascript

Dynamics CRM Adding Notes With JavaScript

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
2 Jan 2014CPOL2 min read 13.7K   2  
Dynamics CRM Adding Notes with JavaScript

In Dynamics CRM, users can add notes to make comments about certain changes that were made to a record. In some instances, there may be a requirement to automate the creation of notes based on certain field information changes.

The challenge with notes is that it is not a field on the entity. It is actually a 1:N association which is displayed on the form with an embedded IFRAME. This means that we can’t just populate a field, but instead, we need to call the REST web services on dynamics to request the creation of the note.

To handle this, we can create a simple JavaScript object that handles the web service call (NoteManager) and another object to handle the test of the creation of the notes (TestNotes):

NoteManager Script:

JavaScript
if (typeof (OGBIT) == "undefined") { OGBIT = {}; }
OGBIT.NoteManager = {
    AddNote: function (params, entitySet, onComplete, onError) {
        var self = OGBIT.NoteManager;
        var serverUrl = self.GetServerUrl();
        var ODataURL = serverUrl + entitySet;
        var json = JSON.stringify(params);      //MUST CONVERT TO JSON STRING

        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            datatype: "json",
            url: ODataURL,
            data: json,
            beforeSend: function (XMLHttpRequest) {
                XMLHttpRequest.setRequestHeader("Accept", "application/json");
            },
            success: function (data, textStatus, XmlHttpRequest) {
                if (onComplete != null)
                    onComplete(data.d.results);
            },
            error: function (XmlHttpRequest, textStatus, errorObject) {
                var msg = textStatus;
                try {
                    msg = JSON.parse(XMLHttpRequest.responseText).error.message.value;
                } catch (e) { }

                if (onError != null)
                    onError(msg);
            }
        });
    },
    GetServerUrl: function () {
        var serverUrl = '';
        if (typeof (Xrm) != 'undefined' && Xrm != null) {
            serverUrl = Xrm.Page.context.getServerUrl();
            //test that server name is not coming back instead of the domain name 
            //otherwise we get a Cross-Origen (CORS) 400 error            
        }
        if (serverUrl.match(/\/$/)) {
            serverUrl = serverUrl.substring(0, serverUrl.length - 1);
        }

        return serverUrl + "/XRMServices/2011/OrganizationData.svc/";
    },
}

The above script implements two main methods:

Method Name Description
AddNote This method handles the interaction with the Dynamics CRM web service. It takes the following parameters:
Name Description
Params JSON structure that contains the note information
entitySet This is the name of the entity where the record needs to be added. For notes, the name is AnotationSet
onComplete This is a callback handler
onError This is a callback handler for errors

Note the following attributes on the request:
The Dynamic CRM web services are RESTFul.
For the creation of a new note, we to set the verb to POST.
Since we pass a JSON structure, we set the content and data types to JSON.
The data parameter contains the JSON data in string format which is generated after calling the stringify function.

GetServerUrl This method resolves the server URL and current organization name.

TestNotes Script:

JavaScript
OGBIT.TestNotes = {
   AddNotes: function () {
      var self = OGBIT.TestNotes;
      var note = {};
      var ref = {};
      note.NoteText = "This is the content of the notes";
      note.Subject = "Note Unit test";
      ref.LogicalName = Xrm.Page.data.entity.getEntityName();//returns the entity name
      ref.Id = Xrm.Page.data.entity.getId();             //returns the primary id/guid
      note.ObjectId = ref;                              //associate the note to an entity
     OGBIT.NoteManager.AddNote(note, 'AnnotationSet', 
               self.onComplete, self.onError); //AnnotationSet is the notes entity set 
    },
    onError: function (msg) {
        alert(msg)
    },
    onComplete: function (data) {
        alert(data);
    }
}

The above script creates the following JSON structures:

Name Description
Note This is the note object notation. It is created with the following attributes:
Name Description
NoteText This is the content for the note
Subject This is the subject
ObjectId This is the object associated to the notes. I.E. A note can be associated to an account or other custom entity that support notes.
ref This is the associated object. It needs the following attributes:
Name Description
LogicalName This is the name of the entity
Id This is the primary id (GUID)
These values can be fetched by using the Xrm client object model. It uses the current context to retrieve the entity information.

After creating the JSON references, the script uses the NoteManager method to post the request to the web services. The callback handlers are called after the web service call has completed.

I hope these scripts can help you get more understanding of the Dynamics CRM web services and how to interact with them via JavaScript.

This article was originally posted at http://ozkary.blogspot.com/feeds/posts/default

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect OG-BITechnologies
United States United States
Software engineer, author & speaker who enjoys mentoring, learning, speaking and sharing with others about software development technologies. Microsoft MVP.

My Blog

Comments and Discussions

 
-- There are no messages in this forum --