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

Monday 8 July 2013

Open an HTML web resource page in a modal dialog, return values from it and use them in the caller Entity form via Javascript / jQuery (CRM 2011)

Sometimes it could be useful to open an external page as a modal window from an entity form and return some values to the caller entity form.
In the following example we show a simple HTML page with an option set and a text box; via javascript, we manage the click on an 'Ok' button to return both the entered text and the chosen option value.
The HTML page could be opened from a ribbon button or in the way that better fit our needs. We show the code snippet to open the modal dialog, take and process the return.



HTML Code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
       <head>
           <title>HTML Web Resource</title>
           <script type="text/javascript"
                      src="../Scripts/jquery_1.9.0.js"></script>
           <script type="text/javascript" language="javascript">

              $(document).ready(function () {
                  var selectedOption;

                  $('#selectmenu').change(function () {
                     // assign the value to variable
                     selectedOption = $('#selectmenu :selected').val();
                  });

                  $('#btnOk').click(function () {
                     var result = {};
                     result.EnteredText = $('#textbox').val();
                     result.SelectedOption = selectedOption;

                     window.returnValue = result;
                     window.close();
                });
            });
           </script>
       </head>
       <body>
        <div>
             <select id="selectmenu">
             <option value="" selected="selected">
                    Select an option
                </option>
                <option value="option1">Option One</option>
                <option value="option2">Option Two</option>
                <option value="option1N">Option N</option>
            </select>
            <br />
            <label>Enter a text: </label>
            <input id="textbox" type="text" />
            <br />
            <input id="btnOk" type="button" value="Ok"/>
        </div>
       </body>
</html>


Code snippet (open dialog):

var retObj = window.showModalDialog('HTML_WebResource_url', null, options);
//Check if the return object is null
if (retObj == null) {
       alert('Error in return');
       return;
}

//Check if returned property 'EnteredText' value is not null

if (retObj.EnteredText) {

    //Use in the form

    Xrm.Page.getAttribute('attribute1_name').setValue(retObj.EnteredText);

}

 
//Check if returned property 'SelectedOption' value is not null
if (retObj.SelectedOption) {
    //Use in the form
    Xrm.Page.getAttribute('attribute2_name').setValue(retObj.SelectedOption);
}
 

Hope it can be useful
Happy CRM coding