Home > Uncategorized > Jscript Reference for Microsoft Dynamics CRM 2011

Jscript Reference for Microsoft Dynamics CRM 2011

Here’s a quick reference guide covering Microsoft CRM 2011’s syntax for common jscript requirements. 

Most of the examples are provided as functions that you can easily test in the OnLoad event of the Account form to see a working example.  These are not production hardened but they’ll help you with the CRM syntax.

(updated: 30 July 2012)

Index:

  1.   Get the GUID value of a Lookup field
  2.   Get the Text value of a Lookup field
  3.   Get the value of a Text field
  4.   Get the database value of an Option Set field
  5.   Get the text value of an Option Set field
  6.   Get the database value of a Bit field
  7.   Get the value of a Date field
  8.   Get the day, month and year parts from a Date field
  9.   Set the value of a String field
  10. Set the value of an Option Set (pick list) field
  11. Set a Date field / Default a Date field to Today
  12. Set a Date field to 7 days from now
  13. Set the Time portion of a Date Field
  14. Set the value of a Lookup field
  15. Split a Full Name into First Name and Last Name fields
  16. Set the Requirement Level of a Field
  17. Disable a field
  18. Force Submit the Save of a Disabled Field
  19. Show/Hide a Field
  20. Show/Hide a field based on a Bit field
  21. Show/Hide a Nav item
  22. Show/Hide a Section
  23. Show/Hide a Tab
  24. Save the form
  25. Save and close the form
  26. Close the form
  27. Determine which fields on the form are dirty
  28. Determine the Form Type
  29. Get the GUID of the current record
  30. Get the GUID of the current user
  31. Get the Security Roles of the current user
  32. Determine the CRM Server URL
  33. Refresh a Sub-Grid
  34. Change the default entity in the lookup window of a Customer or Regarding field
  35. Pop an existing CRM record (new approach)
  36. Pop an existing CRM record (old approach)
  37. Pop a blank CRM form (new approach)
  38. Pop a new CRM record with default values (new approach)
  39. Pop a new CRM record with default values (old approach)
  40. Pop a Dialog from a ribbon button
  41. Pop a URL from a ribbon button
  42. Pop the lookup window associated to a Lookup field
  43. Pop a Web Resource (new approach)
  44. SWITCH statements 
  45. Pop an Ok/Cancel dialog
  46. Retrieve a GUID via REST (default the Price List field)

    1.  Get the GUID value of a lookup field:

    Note: this example reads and pops the GUID of the primary contact on the Account form

    function AlertGUID() { 
        var primaryContactGUID = Xrm.Page.data.entity.attributes.get("primarycontactid").getValue()[0].id; 
        alert(primaryContactGUID); 
    }
    

    2.  Get the Text value of a lookup field:

    Note: this example reads and pops the name of the primary contact on the Account form

    function AlertText() { 
        var primaryContactName = Xrm.Page.data.entity.attributes.get("primarycontactid").getValue()[0].name; 
        alert(primaryContactName); 
    }
    

    3.  Get the value of a text field:

    Note: this example reads and pops the value of the Main Phone (telephone1) field on the Account form

    function AlertTextField() { 
        var MainPhone = Xrm.Page.data.entity.attributes.get("telephone1").getValue(); 
        alert(MainPhone); 
    }
    

    4.  Get the database value of an Option Set field:

    Note: this example reads and pops the value of the Address Type (address1_addresstypecode) field on the Account form

    function AlertOptionSetDatabaseValue() { 
        var AddressType = Xrm.Page.data.entity.attributes.get("address1_addresstypecode"); 
        AddressTypeDisplayValue = AddressType.getValue(); 
        if (AddressTypeDisplayValue != null) { 
            alert(AddressTypeDisplayValue); 
        } 
    }
    

    5.  Get the text value of an Option Set field:

    Note: this example reads and pops the value of the Address Type (address1_addresstypecode) field on the Account form

    function AlertOptionSetDisplayValue() { 
       var AddressType = Xrm.Page.data.entity.attributes.get("address1_addresstypecode"); 
        AddressTypeDisplayValue = AddressType.getSelectedOption().text;
        if (AddressTypeDisplayValue != null) { 
            alert(AddressTypeDisplayValue); 
        } 
    }
    

    6.  Get the database value of a Bit field:

    // example GetBitValue("telephone1");
    function GetBitValue(fieldname) {
        return Xrm.Page.data.entity.attributes.get(fieldname).getValue();
    }
    

    7.  Get the value of a Date field:

    returns a value like: Wed Nov 30 17:04:06 UTC+0800 2011

    and reflects the users time zone set under personal options

    // example GetDate("createdon");
    function GetDate(fieldname) {
        return Xrm.Page.data.entity.attributes.get(fieldname).getValue();
    }
    

    8.  Get the day, month and year parts from a Date field:

    // This function takes the fieldname of a date field as input and returns a DD-MM-YYYY value
    // Note: the day, month and year variables are numbers
    function FormatDate(fieldname) {
        var d = Xrm.Page.data.entity.attributes.get(fieldname).getValue();
        if (d != null) {
            var curr_date = d.getDate();
            var curr_month = d.getMonth();
            curr_month++;  // getMonth() considers Jan month 0, need to add 1
            var curr_year = d.getFullYear();
            return curr_date + "-" + curr_month + "-" + curr_year;
        }
        else return null;
    }
    
    // An example where the above function is called
    alert(FormatDate("new_date2"));
    

    9.  Set the value of a string field:

    Note: this example sets the Account Name field on the Account Form to “ABC”

    function SetStringField() { 
        var Name = Xrm.Page.data.entity.attributes.get("name"); 
        Name.setValue("ABC"); 
    }
    

    10.  Set the value of an Option Set (pick list) field:

    Note: this example sets the Address Type field on the Account Form to “Bill To”, which corresponds to a database value of “1”

    function SetOptionSetField() { 
        var AddressType = Xrm.Page.data.entity.attributes.get("address1_addresstypecode"); 
        AddressType.setValue(1); 
    }
    

    11.  Set a Date field / Default a Date field to Today:

    //set date field to now (works on date and date time fields)
    Xrm.Page.data.entity.attributes.get("new_date1").setValue(new Date());
    

    12.  Set a Date field to 7 days from now:

    function SetDateField() {
        var today = new Date();
        var futureDate = new Date(today.setDate(today.getDate() + 7));
        Xrm.Page.data.entity.attributes.get("new_date2").setValue(futureDate);
        Xrm.Page.data.entity.attributes.get("new_date2").setSubmitMode("always"); // Save the Disabled Field
    }
    

    13.  Set the Time portion of a Date Field:

    // This is a function you can call to set the time portion of a date field
    function SetTime(attributeName, hour, minute) {
            var attribute = Xrm.Page.getAttribute(attributeName);
            if (attribute.getValue() == null) {
                attribute.setValue(new Date());
            }
            attribute.setValue(attribute.getValue().setHours(hour, minute, 0));
    } 
    
    // Here's an example where I use the function to default the time to 8:30am
    SetTime('new_date2', 8, 30);
    

    14.  Set the value of a Lookup field:

    Note: here I am providing a reusable function…

    // Set the value of a lookup field 
    function SetLookupValue(fieldName, id, name, entityType) { 
        if (fieldName != null) { 
            var lookupValue = new Array(); 
            lookupValue[0] = new Object(); 
            lookupValue[0].id = id; 
            lookupValue[0].name = name; 
            lookupValue[0].entityType = entityType; 
            Xrm.Page.getAttribute(fieldName).setValue(lookupValue); 
        } 
    }
    

    Here’s an example of how to call the function (I retrieve the details of one lookup field and then call the above function to populate another lookup field):

    var ExistingCase = Xrm.Page.data.entity.attributes.get("new_existingcase"); 
    if (ExistingCase.getValue() != null) { 
        var ExistingCaseGUID = ExistingCase.getValue()[0].id; 
        var ExistingCaseName = ExistingCase.getValue()[0].name; 
        SetLookupValue("regardingobjectid", ExistingCaseGUID, ExistingCaseName, "incident"); 
    }
    

    15.  Split a Full Name into First Name and Last Name fields:

    function PopulateNameFields() {
        var ContactName = Xrm.Page.data.entity.attributes.get("customerid").getValue()[0].name;
        var mySplitResult = ContactName.split(" ");
        var fName = mySplitResult[0]; 
        var lName = mySplitResult[1]; 
        Xrm.Page.data.entity.attributes.get("firstname").setValue(fName);
        Xrm.Page.data.entity.attributes.get("lastname").setValue(lName);
    }
    

    16.  Set the Requirement Level of a Field:

    Note: this example sets the requirement level of the Address Type field on the Account form to Required. 

    Note: setRequiredLevel(“none”) would make the field optional again.

    function SetRequirementLevel() { 
        var AddressType = Xrm.Page.data.entity.attributes.get("address1_addresstypecode"); 
        AddressType.setRequiredLevel("required"); 
    }
    

    17.  Disable a field:

    function SetEnabledState() {  
        var AddressType = Xrm.Page.ui.controls.get("address1_addresstypecode");  
        AddressType.setDisabled(true);  
    }
    

    18.  Force Submit the Save of a Disabled Field:

    // Save the Disabled Field
    Xrm.Page.data.entity.attributes.get("new_date1").setSubmitMode("always");
    

    19.  Show/Hide a field:

    function hideName() { 
        var name = Xrm.Page.ui.controls.get("name"); 
        name.setVisible(false); 
    }
    

    20.  Show/Hide a field based on a Bit field

    function DisableExistingCustomerLookup() {  
       var ExistingCustomerBit = Xrm.Page.data.entity.attributes.get("new_existingcustomer").getValue(); 
        if (ExistingCustomerBit == false) { 
           Xrm.Page.ui.controls.get("customerid").setVisible(false);  
        } 
        else {
           Xrm.Page.ui.controls.get("customerid").setVisible(true);  
        }
    }
    

    21.  Show/Hide a nav item:

    Note: you need to refer to the nav id of the link, use F12 developer tools in IE to determine this

    function hideContacts() { 
        var objNavItem = Xrm.Page.ui.navigation.items.get("navContacts"); 
        objNavItem.setVisible(false); 
    }
    

    22.  Show/Hide a Section:

    Note: Here I provide a function you can use.  Below the function is a sample.

    function HideShowSection(tabName, sectionName, visible) {
        try {
            Xrm.Page.ui.tabs.get(tabName).sections.get(sectionName).setVisible(visible);
        }
        catch (err) { }
    }
    
    HideShowSection("general", "address", false);   // "false" = invisible
    

    23.  Show/Hide a Tab:

    Note: Here I provide a function you can use. Below the function is a sample.

    function HideShowTab(tabName, visible) {
        try {
            Xrm.Page.ui.tabs.get(tabName).setVisible(visible);
        }
        catch (err) { }
    }
    
    HideShowTab("general", false);   // "false" = invisible
    

    24.  Save the form:

    function SaveAndClose() { 
        Xrm.Page.data.entity.save(); 
    }
    

    25.  Save and close the form:

    function SaveAndClose() { 
        Xrm.Page.data.entity.save("saveandclose"); 
    }
    

    26.  Close the form:

    Note: the user will be prompted for confirmation if unsaved changes exist

    function Close() { 
        Xrm.Page.ui.close(); 
    }
    

    27.  Determine which fields on the form are dirty:

    var attributes = Xrm.Page.data.entity.attributes.get()
     for (var i in attributes)
     {
        var attribute = attributes[i];
        if (attribute.getIsDirty())
        {
          alert("attribute dirty: " + attribute.getName());
        }
     }
    

    28.  Determine the Form Type:

    Note: Form type codes: Create (1), Update (2), Read Only (3), Disabled (4), Bulk Edit (6)

    function AlertFormType() { 
        var FormType = Xrm.Page.ui.getFormType(); 
         if (FormType != null) { 
            alert(FormType); 
        } 
    }
    

    29.  Get the GUID of the current record:

    function AlertGUID() { 
        var GUIDvalue = Xrm.Page.data.entity.getId(); 
        if (GUIDvalue != null) { 
            alert(GUIDvalue); 
        } 
    }
    

    30.  Get the GUID of the current user:

    function AlertGUIDofCurrentUser() { 
        var UserGUID = Xrm.Page.context.getUserId(); 
         if (UserGUID != null) { 
            alert(UserGUID); 
        } 
    }
    

    31.  Get the Security Roles of the current user:

    (returns an array of GUIDs, note: my example reveals the first value in the array only)

    function AlertRoles() {
        alert(Xrm.Page.context.getUserRoles());
    }
    

    32.  Determine the CRM server URL:

    // Get the CRM URL 
    var serverUrl = Xrm.Page.context.getServerUrl(); 
    
    // Cater for URL differences between on premise and online 
    if (serverUrl.match(/\/$/)) { 
        serverUrl = serverUrl.substring(0, serverUrl.length - 1); 
    }
    

    33.  Refresh a Sub-Grid:

    var targetgird = Xrm.Page.ui.controls.get("target_grid"); 
    targetgird.refresh();
    

    34.  Change the default entity in the lookup window of a Customer or Regarding field:

    Note: I am setting the customerid field’s lookup window to offer Contacts (entityid 2) by default (rather than Accounts). I have also hardcoded the GUID of the default view I wish displayed in the lookup window.

    function ChangeLookup() { 
        document.getElementById("customerid").setAttribute("defaulttype", "2"); 
        var ViewGUID= "A2D479C5-53E3-4C69-ADDD-802327E67A0D";
        Xrm.Page.getControl("customerid").setDefaultView(ViewGUID); 
    } 
    

    35.  Pop an existing CRM record (new approach):

    function PopContact() {
        //get PrimaryContact GUID
        var primaryContactGUID = Xrm.Page.data.entity.attributes.get("primarycontactid").getValue()[0].id;
        if (primaryContactGUID != null) {
            //open Contact form
            Xrm.Utility.openEntityForm("contact", primaryContactGUID)
        }
    }
    

    36.  Pop an existing CRM record (old approach):

    Note: this example pops an existing Case record.  The GUID of the record has already been established and is stored in the variable IncidentId.

    //Set features for how the window will appear 
    var features = "location=no,menubar=no,status=no,toolbar=no"; 
    
    // Get the CRM URL
    var serverUrl = Xrm.Page.context.getServerUrl();
    
    // Cater for URL differences between on premise and online
    if (serverUrl.match(/\/$/)) {
        serverUrl = serverUrl.substring(0, serverUrl.length - 1);
    }
    
    window.open(serverUrl + "/main.aspx?etn=incident&pagetype=entityrecord&id=" + encodeURIComponent(IncidentId), "_blank", features, false);
    

    37.  Pop a blank CRM form (new approach):

    function PopNewCase() {
        Xrm.Utility.openEntityForm("incident")
    }
    

    38.  Pop a new CRM record with default values (new approach):

    function CreateIncident() {
        //get Account GUID and Name
        var AccountGUID = Xrm.Page.data.entity.getId();
        var AccountName = Xrm.Page.data.entity.attributes.get("name").getValue();
        //define default values for new Incident record
        var parameters = {};
        parameters["title"] = "New customer support request";
        parameters["casetypecode"] = "3";
        parameters["customerid"] = AccountGUID;
        parameters["customeridname"] = AccountName;
        parameters["customeridtype"] = "account";
        //pop incident form with default values
        Xrm.Utility.openEntityForm("incident", null, parameters);
    }
    

    39.  Pop a new CRM record with default values (old approach):

    Note: this example pops the Case form from the Phone Call form, defaulting the Case’s CustomerID based on the Phone Call’s SenderID and defaulting the Case Title to “New Case”

    //Collect values from the existing CRM form that you want to default onto the new record 
    var CallerGUID = Xrm.Page.data.entity.attributes.get("from").getValue()[0].id; 
    var CallerName = Xrm.Page.data.entity.attributes.get("from").getValue()[0].name; 
    
    //Set the parameter values 
    var extraqs = "&title=New Case"; 
    extraqs += "&customerid=" + CallerGUID; 
    extraqs += "&customeridname=" + CallerName; 
    extraqs += "&customeridtype=contact"; 
    
    //Set features for how the window will appear 
    var features = "location=no,menubar=no,status=no,toolbar=no"; 
    
    // Get the CRM URL
    var serverUrl = Xrm.Page.context.getServerUrl();
    
    // Cater for URL differences between on premise and online
    if (serverUrl.match(/\/$/)) {
        serverUrl = serverUrl.substring(0, serverUrl.length - 1);
    }
    
    //Pop the window 
    window.open(serverUrl + "/main.aspx?etn=incident&pagetype=entityrecord&extraqs=" + encodeURIComponent(extraqs), "_blank", features, false);
    

    40.  Pop a Dialog from a ribbon button

    Note: this example has the Dialog GUID and CRM Server URL hardcoded, which you should avoid.  A simple function is included which centres the Dialog when launched.

    function LaunchDialog(sLeadID) {
        var DialogGUID = "128CEEDC-2763-4FA9-AB89-35BBB7D5517D";
        var serverUrl = "https://avanademarchdemo.crm5.dynamics.com/";
        serverUrl = serverUrl + "cs/dialog/rundialog.aspx?DialogId=" + "{" + DialogGUID + "}" + "&EntityName=lead&ObjectId=" + sLeadID;
        PopupCenter(serverUrl, "mywindow", 400, 400);
        window.location.reload(true);
    }
    
    function PopupCenter(pageURL, title, w, h) {
        var left = (screen.width / 2) - (w / 2);
        var top = (screen.height / 2) - (h / 2);
        var targetWin = window.showModalDialog(pageURL, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
    }
    

    41.  Pop a URL from a ribbon button

    Great info on the window parameters you can set here:  http://javascript-array.com/scripts/window_open/

    function LaunchSite() {
        // read URL from CRM field
        var SiteURL = Xrm.Page.data.entity.attributes.get("new_sharepointurl").getValue();
        // execute function to launch the URL
        LaunchFullScreen(SiteURL);
    }
    
    function LaunchFullScreen(url) {
     // set the window parameters 
     params  = 'width='+screen.width;
     params += ', height='+screen.height;
     params += ', top=0, left=0';
     params += ', fullscreen=yes';
     params += ', resizable=yes';
     params += ', scrollbars=yes';
     params += ', location=yes';
    
     newwin=window.open(url,'windowname4', params);
     if (window.focus) {
         newwin.focus()
     }
     return false;
    }
    

    42.  Pop the lookup window associated to a Lookup field:

    window.document.getElementById('new_existingcase').click();
    

    43.  Pop a Web Resource (new approach):

    function PopWebResource() {
        Xrm.Utility.openWebResource("new_Hello");
    }
    

    44. Using a SWITCH statement

    function GetFormType() {
        var FormType = Xrm.Page.ui.getFormType();
        if (FormType != null) {
            switch (FormType) {
                case 1:
                    return "create";
                    break;
                case 2:
                    return "update";
                    break;
                case 3:
                    return "readonly";
                    break;
                case 4:
                    return "disabled";
                    break;
                case 6:
                    return "bulkedit";
                    break;
                default:
                    return null;
            }
        }
    }
    

    45.  Pop an Ok/Cancel Dialog

    function SetApproval() {
        if (confirm("Are you sure?")) {
            // Actions to perform when 'Ok' is selected:
            var Approval = Xrm.Page.data.entity.attributes.get("new_phaseapproval");
            Approval.setValue(1);
            alert("Approval has been granted - click Ok to update CRM");
            Xrm.Page.data.entity.save();
        }
        else {
            // Actions to perform when 'Cancel' is selected:
            alert("Action cancelled");
        }
    }
    

    46.  Retrieve a GUID via REST (default the Price List field)

    In this example (intended for the Opportunity form’s Onload event) I execute a REST query to retrieve the GUID of the Price List named “Wholesale Price List”.  I then execute the DefaultPriceList function to default the Price List field.  As this uses REST your CRM form will need json2 and jquery libraries registered on the CRM form (I have these libraries in a solution file I import when needed):

    image

    function RetrieveGUID() { 
        // Get CRM Context
        var context = Xrm.Page.context; 
        var serverUrl = context.getServerUrl(); 
        // Cater for URL differences between on-premise and online 
        if (serverUrl.match(/\/$/)) { 
            serverUrl = serverUrl.substring(0, serverUrl.length - 1); 
        }
        // Define ODATA query
        var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc"; 
        var ODATA_EntityCollection = "/PriceLevelSet"; 
        var PriceListName = 'Wholesale Price List';
        var QUERY = "?$select=PriceLevelId&$filter=Name%20eq%20'" + PriceListName + "'&$top=1";
        var URL = serverUrl + ODATA_ENDPOINT + ODATA_EntityCollection + QUERY;
        //Asynchronous AJAX call 
        $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            datatype: "json",
            url: URL,
            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) {
                //This function will trigger asynchronously if the Retrieve was successful
                var GUID_Retrieved = data.d.results[0].PriceLevelId;
                DefaultPriceList(GUID_Retrieved, PriceListName); 
            },
            error: function (XmlHttpRequest, textStatus, errorThrown) {
                //This function will trigger asynchronously if the Retrieve returned an error
                alert("ajax call failed");
            }
        });
    }
    
    function DefaultPriceList(GUID, NAME){
            var lookupValue = new Array(); 
            lookupValue[0] = new Object(); 
            lookupValue[0].id = GUID; 
            lookupValue[0].name = NAME; 
            lookupValue[0].entityType = "pricelevel"; 
            Xrm.Page.getAttribute("pricelevelid").setValue(lookupValue); 
    }
    


    Here is a little more info that will help you get your head around the general design of all this…

    Depending upon what you want to do you will interact with one of the following:

    Xrm.Page.data.entity.attributes – The data fields represented by fields on the form

    Xrm.Page.ui.controls – The user interface controls on the form

    Xrm.Page.ui.navigation.items – The navigation items on the form

    Xrm.Utility – A container of helpful functions

    When referring to fields or controls you must specify the name of the field and surround with quotes (and make sure you get the case right):

    image

    When referring to nav items you must specify the nav ID and surround it with quotes.  To determine the nav ID:

    - open the CRM form in IE

    - hit F12 to activate IE’s developer tools (if it doesn’t appear, check for it under Task Manager and maximise it from there)

    - in the developer tools window click the arrow to activate the “Select element by click” mode

    - on the CRM form click the nav item (the dev tools window will take you to HTML definition of that element)

    image

    - just above there you will see the nav ID specified, look for id=”nav<something>”

    image

    When setting properties to true/false do not surround the true/false value with quotes.

    Typically there are 2 steps to interacting with fields.  First you get the field as an object.  Then you interact with that object to get or set the property value you are interested in.

    Here’s an excellent post that provides a comparison of CRM v4 syntax and CRM 2011:

    http://community.dynamics.com/product/crm/crmtechnical/b/crminogic/archive/2011/02/19/difference-between-crm-4-0-and-crm2011-script-for-using-on-form-customization.aspx

    And here’s a download containing similar code snippets but provisioned as installable Visual Studio code snippets (something I wasn’t aware of but think is pretty cool!).

    Here’s another useful jscript list:  http://andreaswijayablog.blogspot.com/2011/07/crm-2011-javascript-functions.html

    About these ads
    1. March 23, 2011 at 12:19 am | #1

      very useful information
      thank you

    2. Pedro
      April 8, 2011 at 7:04 am | #2

      Very useful, thanks! One question though… How do I make a field disabled (readonly) in CRM 2011?

    3. Pete
      August 2, 2011 at 6:45 pm | #4

      Hi,
      A new CRM fellow like me, it is very helpful for qucik reference, saved lot of develop time.

      I found few more other syntaxes useful in below site
      http://rajeevpentyala.wordpress.com/2011/07/23/useful-crm-2011-jscript-syntaxes/

    4. Rajesh
      October 7, 2011 at 5:26 pm | #5

      Thank you… This is a very nice Article.

    5. October 28, 2011 at 7:58 pm | #6

      Excellent article, thanks!

    6. November 14, 2011 at 9:27 pm | #7

      Thanks for the article. It is very useful.

    7. alex
      December 9, 2011 at 1:02 am | #8

      Thanks! Great article! I’m a CRM beginner and your article helped me a lot!

    8. December 15, 2011 at 4:13 pm | #9

      Thanks….

    9. Aad
      January 5, 2012 at 7:23 am | #10

      Can I just say your scripts have saved my life so many times by now, thanks a million and keep it up! Aad

    10. Rajesh Achanta
      January 6, 2012 at 9:35 pm | #11

      This is a fantastic article. I’ve used it several times but never had a chance to say ‘Thanks’. So ‘Thank you’ for the knowledge sharing.

    11. January 19, 2012 at 9:37 am | #12

      Kick butt man, great post

    12. Pedro
      January 20, 2012 at 3:36 am | #13

      Great post Gareth!

      Quick question. When hiding fields in a form the space where field use to be is still there… Is there a way to collapse the empty space?

      I could swear that in my previous CRM deployments there would be no space when the field is hidden (?!)

    13. NAG
      January 30, 2012 at 3:20 am | #15

      very good info.. thanks a lot..

    14. Aree
      January 31, 2012 at 5:15 am | #16

      These are helpful CRM 2011 tips! :) thanks Gareth!

    15. Jeremy
      February 10, 2012 at 3:22 pm | #17

      Awesome stuff! I’m trying to populate the Shipping Address on the Quote for onChange of the Customer (customerid). Can anyone point me in the right direction?

      • February 10, 2012 at 4:51 pm | #18

        Hi, I take it you need to read the address off of the Customer record and write that into the fields on the quote form? Basic jscript isn’t going to be able to do that as the data you want to read is not on the form, you need to reach back to the server for that data. You could write a workflow to do this but the behaviour would be asynchronous which is likely an issue. Or you can write a .net plugin, that can be synchronous but you will still not the fields populated until the save (you could trigger the save as soon as the customer is selected, but that is still not the ideal user experience and you might have other mandatory fields that will cause issue). Last option is to use jscript + jquery. Write a jquery/ajax call to the REST end point to retrieve the address data and then use basic jscript to populate the fields on the form. I’ve written some posts about using REST. It’s not too hard, just slightly trickier jscript really. Good luck.

    16. February 15, 2012 at 5:33 pm | #19

      Very Very useful functions..

    17. Randall Smith
      February 18, 2012 at 11:18 am | #20

      Great information! – thanks for putting this together – any idea how to make a look-up field read-only> when I use setDisabled(true) I get an error – Thanks

    18. February 19, 2012 at 10:17 am | #21

      Very handy tips, Gareth – thank you for your time and effort

    19. February 20, 2012 at 9:48 pm | #22

      Very helpful, much appreciated.

    20. Amanpreet
      February 22, 2012 at 8:00 pm | #23

      Very Nice and helpful Article ,Thank You keep posting :)

    21. sumit
      March 16, 2012 at 9:04 pm | #24

      Thanks a lot for this descriptive summary of Javascript client framework for crm!

    22. Dave H
      March 21, 2012 at 1:17 am | #25

      Excellent work! VERY useful!

    23. March 28, 2012 at 1:33 am | #26

      Awesome! Wish I would have had a month of go, would have saved the learning curve.

    24. Rick W
      April 15, 2012 at 3:56 am | #27

      Great stuff! How would you format a field on a form where I truncate the first 3 characters. So field1 = ” _012345″. On form load i want to read field1 reformat it, place it in field 2 so it Displays “2345″. Field 1 would remain “_012345″ and field 2 would contain the value “2345″ because it trucated the first 3 characters. I have a funky account number field that I need to keep but sales wants it to display in a different field with this format. thanks.

    25. Vijay
      April 16, 2012 at 2:24 pm | #29

      Very Good!!

    26. Kristin
      April 18, 2012 at 3:46 am | #30

      I am trying to use your jscript for getting the day, month, and year parts from a date field but I am receiving an error on the page. I am quite new to this, is that script supposed to go on the field change event or onload event? I am only looking for the day part of the field and I would like to put it into another text field on same form. Thanks!

      • April 18, 2012 at 10:09 pm | #31

        Hi, my understanding is you have a date field and a text field and you want to extract the day from the date field and write that to the text field whenever the date field is populated or changed. Create a web resource with the neccessary jscript in it. Reference that web resource and the specific function inside it to fire on the OnChange event of the date field. Steal from my function lines 4 and 6 to read the date field and then extract the day portion of that value. And then refer to “Set the value of a String field”. HTH

    27. Akhil
      April 23, 2012 at 9:36 pm | #32

      Very Use full, thanks

    28. April 25, 2012 at 7:47 pm | #33

      Hi gareth,

      For some reason the hide/show tab script doesn’t seem to work. It doesn’t return any errors, but all that it does is hide the tab name within the nav menu on the left-hand side menu.

      I use this post as reference a LOT and this is the only one I have issues with. The hide/show section works great, though.

      Any ideas?

      Cheers,
      P.

      • April 25, 2012 at 9:57 pm | #34

        Just retested my HideShowTab function on the Quote form’s OnLoad event against the Addresses tab and it works as expected for me, the Tab dissapears from the form and from the navagation pane’s Tab list. Perhaps you have other code making a field or section within that Tab visible? Or a required field on that Tab?

    29. April 28, 2012 at 2:31 am | #35

      Gareth,

      Sorry, I was brain dead when I tried… My bad! It is working as expected.

    30. kdellavalle
      May 1, 2012 at 3:16 am | #36

      This is a beautiful post! Now I never have to actually remember any of these. Thanks!

    31. beege
      May 4, 2012 at 6:19 am | #37

      Kudos! Thank you for sharing!

    32. Christina
      May 5, 2012 at 12:21 am | #38

      One of the best posts that I have seen. Thank you so much for all of this info in such a well, organized fashion!! This just helped me with about 5 different js issues I was having. Thank you again!!!

    33. Nidhi
      May 8, 2012 at 8:18 pm | #39

      Very Good and Useful Post.

      Thanks Gerath

    34. Bruce
      May 17, 2012 at 10:11 am | #40

      Thanks for the help Gareth ;-)

    35. Alexandre
      May 22, 2012 at 5:06 am | #41

      Great Post. Thank You!!

    36. MeProgrammer
      May 24, 2012 at 1:44 am | #42

      Thanks for all the great examples.
      Question: In your code

      function AlertGUID() {
      var GUIDvalue = Xrm.Page.data.entity.getId();
      if (GUIDvalue != null) {
      alert(GUIDvalue);
      }
      }

      Does this retrieve the GUID of the form or the GUID of the entity whose form it is?

    37. June 26, 2012 at 9:01 pm | #43

      Gareth,

      How would you show/hide a webresource? I tried the following but it didn’t work:

      Xrm.Page.ui.controls.get(“WebResource_name”).setVisible(true);

      Any ideas?

      Cheers,
      P.

    38. niraj
      June 30, 2012 at 1:19 pm | #44

      thanks, you save lot of the time .

    39. July 11, 2012 at 12:47 am | #45

      awesome post!

    40. Allen Campbell
      July 11, 2012 at 11:20 pm | #46

      I must admit you make my life a lot easier ;-)

    41. vijay
      July 16, 2012 at 9:13 pm | #47

      Great Job :-)

    42. Kishore Amireddy
      July 20, 2012 at 4:18 pm | #48

      Gareth, thanks for the wonderful work!

    43. Zach
      July 31, 2012 at 12:30 am | #49

      I was excited to find this great site. I wanted to thank you for ones time just for this wonderful read!! I definitely liked every little bit of it and i also have you book-marked to see new stuff in your blog.

      http://www.isinc.com/training/microsoft-sharepoint/

    44. August 18, 2012 at 4:09 am | #50

      I’ve had no luck getting the new “Xrm.Utility.openEntityForm” method to work on any of my CRM Online environments (I’ve tried it across several different scenarios)…I always get an error saying: “Unable to get value of the property ‘openEntityForm’: object is null or undefined.”

      Has “Xrm.Utility.openEntityForm” been implemented universally for CRM Online? Is anyone else having similar trouble?

    45. Ritesh
      August 31, 2012 at 6:36 pm | #52

      Some more useful javascripts such as get record id of the form and display of a control

      / Get the label of the control
      Xrm.Page.ui.controls.get(‘wwb2c_approved’).getLabel()
      // Get record id
      crmForm.ObjectId –> Xrm.Page.data.entity.getId()

      // set field as required based value of a check box field.

      function OnChangeBoolField()
      {
      var varBool = Xrm.Page.data.entity.attributes.get(“boolFieldName”).getValue();
      if(varBool == false)
      {
      Xrm.Page.getAttribute(“new_startdate”).setRequiredLevel(“required”);
      Xrm.Page.getAttribute(“new_dueby”).setRequiredLevel(“required”);
      }
      else
      {
      Xrm.Page.getAttribute(“new_startdate”).setRequiredLevel(“none”);
      Xrm.Page.getAttribute(“new_dueby”).setRequiredLevel(“none”);
      }
      }
      // Compare Dates
      function ValidateDates()
      {

      var startdate = Xrm.Page.getAttribute(‘new_startdate’).getValue();
      var dueby = Xrm.Page.getAttribute(‘new_dueby’).getValue();

      if(startdate != null && dueby != null)
      {
      if(dueby.setHours(0,0,0,0) < startdate.setHours(0,0,0,0))
      {
      alert('Due By must be greater than or equal to Start Date');
      event.returnValue = false;
      return false;
      }
      }
      }

    46. Pankaj Joshi
      September 16, 2012 at 1:56 pm | #53

      Is it possible to update all the records of an entity simultaneously. Eg i have 2 attribute in my entity and i need to update 1 attribute with the value in the other attribute. This needs to be done for all the records. can some one help me out here.
      Thanks.

      • September 16, 2012 at 8:47 pm | #54

        Sounds like you have a one time requirement to duplicate a field value to another field for all records in a table. Your options on CRM 4.0 are .net scripting (console app against crm’s web services), SQL update (but unsupported), use a 3rd party tool like Scribe.

        • Pankaj Joshi
          September 16, 2012 at 10:08 pm | #55

          Can you pls suggest me some links where i could see how to do this .net scripting for CRM. Since i’ am pretty new to CRM i don’t know much about it.

        • September 16, 2012 at 11:02 pm | #56

          Download the SDK and check out the sample code there.

        • RickW
          September 18, 2012 at 1:15 am | #57

          If this is a one time update you should just do it in a SQL statement on the DB, it’s just a couple of lines of code. It may technically not supported but it will work without issue. Run it in a test Environment first. I also like to run a select statement and verifiy my fields. So the update Statement would be something like this:

          USE NameOfDatabase;

          UPDATE TableName
          SET Field1 = Field2
          FROM TableName
          WHERE

          If you leave the Where Clause off it will update all the records. You may want to add a specific Where clause to test a single record first. Something like (Where Order_no = ’12345′).

          You can Google a million code examples how to do this.

          ..

    47. Pankaj Joshi
      September 16, 2012 at 2:09 pm | #58

      The above problem is for CRM 4.0.

    48. December 7, 2012 at 7:58 pm | #59

      excellent outstanding perfect superb!!

    49. Mark DSouza
      February 25, 2013 at 2:16 pm | #60

      excellent post :) thank you for the info

    50. sowmya
      March 19, 2013 at 9:56 pm | #61

      I have referred this page a lot of times and made saved it as fav pg. very easy to refer soon… GR8 Job!!! thanks:)

      I want a particular field value in service activity to get updated in the selected resource’s(user’s) form’s field… how this can be achieved??? plz help:(

    1. September 7, 2011 at 7:46 pm | #1
    2. September 20, 2011 at 1:31 am | #2
    3. October 1, 2011 at 5:55 am | #3
    4. October 29, 2011 at 2:55 am | #4
    5. April 16, 2012 at 11:39 am | #5
    6. April 17, 2012 at 12:14 am | #6
    7. April 24, 2012 at 7:25 pm | #7

    Leave a Reply

    Fill in your details below or click an icon to log in:

    WordPress.com Logo

    You are commenting using your WordPress.com account. Log Out / Change )

    Twitter picture

    You are commenting using your Twitter account. Log Out / Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out / Change )

    Connecting to %s

    Follow

    Get every new post delivered to your Inbox.

    Join 370 other followers

    %d bloggers like this: