JoeCode

TIL: Post an annotation to a Dynamics CRM account record's timeline

May 09, 2023

Simple script to add an annotation note to a regarding account’s timeline when a custom form is saved.

/// Unique NameSpace
var MyCustomForm = window.MyCustomForm || {};
// Anonymous Function
(function () {
  // OnSave Event
  this.formOnSave = function (executionContext) {
    var form_context = executionContext.getFormContext();
    // Determine regarding account using a custom attribute value
    var regarding_account = form_context.getAttribute("new_my_clientid_attribute").getValue();
    if (regarding_account !== null && regarding_account.length == 1) {
      // Get the ID
      var account_id = regarding_account[0].id
      // Prep ID for annotation request
      account_id = account_id.replace("{","(");
      account_id = account_id.replace("}",")");
      // Form Type (create, update, etc...)
      var form_type = form_context.ui.getFormType();
      // Annotate Account if the form is updated
      if (form_type == 2) {
        // Build Annotation (note) object
        var note = {};
        note.subject = "My Custom Form Updated";
        var form_url = form_context.getUrl();
        var form_anchor = "<a href=\"" + form_url + "\">" + form_url + "</a>"
        note.notetext = "URL to Form: " + form_anchor;
        note.isdocument = false;
        note["objectid_account@odata.bind"] = "/accounts"+account_id;
        // Create Annotation Record
        Xrm.WebApi.createRecord("annotation", note);
      }
    }
  }
}).call(MyCustomForm);

References