Wednesday, January 19, 2011

CRM 2011: Running JScript Code Interactively in IE 8

While working on client-side code in Dynamics CRM, it's often faster to write and test the code incrementally within the context of a a "live" form, so that adjustments can be made quickly. Then, once a block of code is working, most of it can be moved to a code library to be further tested in CRM.

This article shows how to run jscript (javascript) code within an account form to format a phone number. The process utilizes the "Run Script" features in the Developer Tools utility that's included with Internet Explorer 8. The code assumes you are working in Dynamics CRM 2011.

Step 1: Load the CRM form upon which you want to run/test JScript code. For this example, load the Account form since the value of the “telephone1” field will be reformatted later in the example.

Step 2: Enter an unformatted phone number in the Main Phone (telephone1) field.  Example: 4255551212

Step 3: In IE, press F12 to load the Developer Tools window.

Step 4: Click Script and then click the Multi Line Mode button.

Step 5: Run the script shown below.
// Reference the main form window (iframe)

var oWindow = document.getElementById("contentIFrame").contentWindow;

// Reference the field with the phone number to format.
var oField = oWindow.Xrm.Page.data.entity.attributes.get("telephone1");

// Remove any non-numeric characters from the field's data.
var sTmp = oField.getValue().replace(/[^0-9]/g, "");

// If the number has a valid length, format the number.
switch (sTmp.length)
{
case "4255551212".length:
  oField.setValue("(" + sTmp.substr(0, 3) + ") " + sTmp.substr(3, 3) + "-" + sTmp.substr(6, 4));
  break;
case "5551212".length:
  oField.setValue(sTmp.substr(0, 3) + "-" + sTmp.substr(3, 4));
  break;
}
Step 6: View the Main Phone field again in the account form. The value should be formatted as (nnn) nnn-nnnn.

No comments:

Post a Comment