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

Thursday, 27 June 2013

Enabling/Disabling "New Activity" ribbon button based on an attribute value of the record with a custom Javascript function and Ribbon Workbench (CRM 2011)

We have had the need to enable or disable the "New Activity" button on the ribbon of the Incident entity based on the value of a record attribute.
We were inspired from an answer on a similar question on the Microsoft social community. We have followed this solution as base and extended it with a custom Javascript function to achieve our purposes.
The question and answers mentioned above are at the following URL:

http://social.microsoft.com/Forums/en-US/a5a0666f-8a07-4b25-92a3-e36ce8861d04/crm-2011-how-to-disable-the-new-activity-ribbon-button-for-a-deactivated-custom-entity
This solution allow the enabling/disabling based on the status of the record (Active / Inactive).

First of all we have developed the Javascript function similar the following:
function addNewActivityEnableRule() {
    //Retrieve the parent window Page object
    var parentPage = document.parentWindow.parent.Xrm.Page;

    //Gets the desired attribute of the parent window page
    var parentPageAttribute = parentPage.getAttribute('parentPage_attributeName');

    //Check if attribute exists
    if (parentPageAttribute) {
      //Get the value of the attribute
        var parentPageAttributeValue = parentPageAttribute.getValue();

        //'value_for_enabling' : replace with the desired value
          (or extend the condition as needed)
        //Return true for the conditions where you want enable
          the ribbon button and false otherwise
        if (parentPageAttributeValue == 'value_for_enabling') {
            return true;
        } else {
            return false;
        }
    }
}

Our solution consists of the following steps:
1. Create a solution with the ‘Activity’ entity in it
2. Open the Solution in the Ribbon Workbench

3. Select 'Activity' entity (activitypointer)
4. Select the 'SubGrid' ribbon in the top right drop down
5. Select the 'New {0}' button and right-click -> Customise Command. Don’t select 'Customise Button'!


 
6. In the 'Solution Elements', expand the 'Display Rules' and for each display rule, set the 'IsCore' property to 'True' since we don’t want to customise these – only the command.
7. In the 'Solution Elements', expand the 'Commands' and select the 'Mscrm.NewRecordFromGrid' command and Right-Click ->'Edit Enable Rules'
8. Click 'Add New' and then 'Add Step'. Select a 'Custom Javascript Rule'

 

9. Set the properties:
      1. InvertResult: False
      2. Default: False


10. Provide the function name and the web resource script library where the function resides
11. Click 'Publish Solution'


Hope it can be useful
Happy CRM coding