Monday, 29 July 2013

Clone an entity record via JavaScript (CRM 2011)

We have had the need to clone a record with client-side Scripting, responding to a click on a button in the entity's Ribbon.
Conceptually the operation is easy and is based on the retrieving of all the record information using the Organization web service, then build an object identical to the first and use the web service to create a new record with this object.
Few things are important to take in mind:
1. In the building of the object the record ID must be "skipped" because, obviously, we can't create a record with an existing Guid
2. Date fields are returned in a format like: "Date("date_string") that it is not accepted in record creation from the Organization web service: depending of the need of every field, we decided to "skip it" or "reformat it". In the sample code we show both of these cases.
3. StateCode and StatusCode should be skipped (or managed) because, natively, Organization web service doesn't allow the creation of a record in a closed state.


function cloneRecord(serverUrl, originRecordType, originRecordGuid) {
    var cloneData = {};
    var activityId;
    var serverUrl = document.location.protocol + "//" + document.location.host
                    + "/"Xrm.Page.context.getOrgUniqueName();
    var oDataUri = serverUrl + "/xrmservices/2011/OrganizationData.svc/" 
                   originRecordType + "Set?$select=*&$filter=<EntityId> eq guid'"
                   + originRecordGuid + "'";
    jQuery.support.cors = true;
    jQuery.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: oDataUri,
        async: false, //Synchronous operation 
        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) {
            if (data && data.d && data.d.results) {
                cloneData = data.d.results[0];
                //Here insert the code to skip/transform fields such as
                  Record Id, Date fields, etc..
                replacer = function (key, value) {
                    if (key == "ModifiedOn" || key == originRecordType + "Id" ||
                        key == "CreatedOn" || key == "StateCode" ||
                        key == "StatusCode") {
                       
                        return undefined;
                    } else if (key == "ActualStart" || key == "ActualEnd") {
                        if (value) {
                            var date =
                            eval('new ' +
                               value.replace("/", "").replace("/", ""));
                            return date.format('yyyy-MM-dd'); //Format the date
                        }
                    }
                    else return value;
                }
                //Create new Activity
                var oDataUri = serverUrl +
                               "/xrmservices/2011/OrganizationData.svc/" +
                               originRecordType + "Set";
                jQuery.support.cors = true;
                jQuery.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    datatype: "json",
                    url: oDataUri,
                    async: false, //Synchronous operation 
                    data: JSON.stringify(cloneData, replacer),
                    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) {
                        if (data && data.d) {
                            activityId = data.d.ActivityId;
                        }
                    },
                    error: function (XmlHttpRequest, textStatus, errorThrown) {
                      alert("Error :  has occured during creation of
                              the activity "  + originRecordType.text + ": " +
                             XmlHttpRequest.responseText);
                    }
                });
            } else {
                //No data returned
            }
        },
        error: function (XmlHttpRequest, textStatus, errorThrown) {
            alert("Error :  has occured during retrieving of the activity "
                    + originRecordType.text + ": " +
                    XmlHttpRequest.responseText);
        }
    });
    return activityId;
}
Hope it can be useful
Happy CRM coding

Rate this posting:
{[['']]}

6 comments:

  1. Awesome Article.
    Really helpfull for all CRM Worms

    ReplyDelete
  2. Very nice article. I have a question: Is there a way to determine whether a certain attribute is a 'date/time' type attribute ?

    ReplyDelete
    Replies
    1. Hi Rajes.
      Thanks for your appreciation.
      Unfortunately, I am quite sure that there is no way to determine the data type from the JSON string returned from the CRM organization web service.
      As you can read the answers of a similar question here:
      http://stackoverflow.com/questions/13869762/how-to-determine-property-type-from-json
      1. Javascript is not strongly-typed
      2. JSON is a string coming from the serialization of data and not types

      If your "goal" is trying to generalize and to abstract from the attribute names, perhaps you could parse the value and searching the string "Date" as returned from the CRM organization web service.
      I know that it is not a "clean solution", but personally I don't see another way.

      Please, if you find something interesting, share it with me.

      Delete
  3. how can we use it?????

    ReplyDelete
  4. how do you call the function with the correct parameters?

    ReplyDelete
  5. Hey there. I found your web site by the use of Google while searching for a related topic, your website got here up. It appears to be good. I have bookmarked it in my google bookmarks to visit then.
    saas vendor

    ReplyDelete