JavaScript Reference for Microsoft Dynamics CRM 2011 / 2013

Here’s a quick reference guide covering Microsoft CRM 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 AddressTypeDBValue = Xrm.Page.data.entity.attributes.get("address1_addresstypecode").getValue();
    if (AddressTypeDBValue != null) {
        alert(AddressTypeDBValue);
    }
}

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 AddressTypeDisplayValue = Xrm.Page.data.entity.attributes.get("address1_addresstypecode").getText();
    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

98 thoughts on “JavaScript Reference for Microsoft Dynamics CRM 2011 / 2013

  1. Pingback: Java Script Reference–Updated « Gareth Tucker's Microsoft CRM Blog

  2. Pingback: Java Script Reference for Microsoft CRM 2011 « mydynamicscrm

  3. Pingback: CRM2011, OData, JSON, JQuery -Kevin's Mocha

  4. Pingback: More CRM 2011 Javascript -Kevin's Mocha

  5. Rajesh Achanta

    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.

    Reply
  6. Pedro

    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 (?!)

    Reply
  7. Jeremy

    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?

    Reply
    1. Gareth Tucker Post author

      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.

      Reply
  8. Randall Smith

    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

    Reply
  9. Rick W

    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.

    Reply
  10. Pingback: Reusable Jscript Library of Common Functions for CRM 2011 « Gareth Tucker's Microsoft CRM Blog

  11. Pingback: Jscript Reference for Microsoft CRM 2011 « Crm 2011 Tips

  12. Kristin

    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!

    Reply
    1. Gareth Tucker Post author

      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

      Reply
  13. Pingback: Dynamics CRM: The importance of the Address entity | Pedro Innecco

  14. pmdci

    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.

    Reply
    1. Gareth Tucker Post author

      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?

      Reply
  15. Christina

    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!!!

    Reply
  16. MeProgrammer

    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?

    Reply
  17. pmdci

    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.

    Reply
  18. Derek

    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?

    Reply
  19. Ritesh

    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;
    }
    }
    }

    Reply
  20. Pankaj Joshi

    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.

    Reply
    1. Gareth Tucker Post author

      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.

      Reply
      1. Pankaj Joshi

        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.

      2. RickW

        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.

        ..

  21. sowmya

    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:(

    Reply
  22. KetanMehta

    Hi,
    This is a great article. I have one question… Can I get an entity’s default view name if I only know the name or the entity or entity type code? For example, entity “account”.
    I want to get the default view name (“AccountSet”) in javascript.. how achieve this?

    Reply
  23. Adam

    Hi, tried to use the pop dialog js but i get incorrect url to launch a dialog.

    Is there anything wrong:

    function TestRibbon(sLeadID)
    {
    var DialogGUID = “6D128DF9-F51A-4D97-912D-C5A1FA4CEAFB”;
    var serverUrl = “https://ebcgroup.ebcgroup.co.uk:444/”;
    serverUrl = serverUrl + “cs/dialog/rundialog.aspx?DialogId=” + “{” + DialogGUID + “}” + “&EntityName=lead&ObjectId=” + sLeadID;
    PopupCenter(serverUrl, “mywindow”, 400, 400);
    window.location.reload(true);
    }

    Reply
  24. Edwin

    HI i have a tab called General and has one section called general as well. i want to disable all the fields in the tab based on the value of a bit field. what is the correct syntax for that function?

    Reply
  25. Pingback: All java script examples: | jadanaren

  26. Naga Raju Padala

    Hi,
    I have written the JavaScript code for crm 2011, but after crm upgradation to 2013,
    that code not working in crm 2013. After up-gradation to crm 2013 the lookup is missing its multi value functionality.
    so i need to change below code:
    document.getElementById(“new_product”).setAttribute(“lookupstyle”, “multi”);

    can anyone help on this.
    Thanks in advance

    Reply
  27. jadanarendra

    Hi Gareth Tucker,

    I Have One Question.
    How to remove option set values in Onload event using java script.
    scenario: Stage is option set —values are A,B,C like.
    when Onload event remove B,C value in the stage field.

    please give me replay ..

    Reply
  28. jadanarendra

    Hi Gareth Tucker,

    I got one error: when i open the activities in mscrm 2011, Please send me answer.

    An Error has occurred. Try this action again.if the problem contines,check the microsoft dynamics crm community for solutions or contact your organization’s microsoft dynamics crm administrator.Finally, you can contact Microsoft support.

    Regards,
    Narendra

    Reply
  29. Pingback: Microsoft Dynamics CRM Top Links | Adrian Vinnicombe

  30. venkatesh k

    4. 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.
    1
    2
    3
    4
    5

    function ChangeLookup() {
    document.getElementById(“customerid”).setAttribute(“defaulttype”, “2”);
    var ViewGUID= “A2D479C5-53E3-4C69-ADDD-802327E67A0D”;
    Xrm.Page.getControl(“customerid”).setDefaultView(ViewGUID);
    }
    the above code is not working in crm 2013.if any one knows please help me.

    Reply
  31. Pingback: ms crm dynamics tutorial links | dotnetqueries

  32. jadanarendra

    Hi Garethtucker,

    1: N relationship mapping on Quick Create Form in mscrm 2013

    Quick create form when opened from a Sub-Grid by clicking the ‘+’ symbol will also use the respective relationship mappings. Here it seems the Quick Create form is caching the data as when we change the mapped field values, save the parent form and clikc on the ‘+ ‘ symbol will still show old values for the mapped fields. Any suggestion or fix can I get please.

    Ex: On Account, I have a Recent Opportunities (1:N) sub-grid that displays all the related Opportunity records for the Account. In the 1:N relationship mapping I have mapped Account.Segment to Opportunity.Segment. The real issue comes when I change the Account.Segment value and try to add a new Recent Opportunity then the Opportunity Quick create form shows the old Segment value of Account whereas it should the new value.

    Please help me….

    Reply
  33. Shaun Harrison

    Hi
    With regards to the grid, do you know any javascript code that can help me retrieve the names of the items that are in a grid

    I’ve managed to get the ID’s via the following:

    var gridControl = document.getElementByID(‘salesorderdetailsGrid’).control;
    var ids = gridControl.get_allRecordIds();

    However I have been unsuccessful at getting anything from there

    Thanks

    Reply
  34. CP

    Hi,

    In CRM 2013 I have an optionset, and when an option is selected certain child fields are visible. These child fields contain two-options (Yes/No). What I need to do is if the User changes which option they have selected then the selection made in the child-field type is reset and previous selections are cleared. I tried adding Xrm.Page.getControl(“attribute”).setValue(null); within my function but this didn’t work and subsequently showed the child-fields for options selections where is it set to .setVisible(false). Can anyone advise?

    Reply
  35. Pingback: Development 101: working with parameters | Journey into CRM

  36. Pingback: Development 101: working with parameters - Microsoft Dynamics CRM Community

  37. Ulrich Faden

    Hi Gareth,
    thanks for this detailed collection of useful functions!
    Do you have any apporach to find a lookup-id from an entity above to set in the antity below?
    Ex: I am in a quote and want to set a lookup-field with the value (id) from the parent account record. Is this complicated?
    Thanks Ulrich

    Reply
  38. Pingback: Javascript Reference for Microsoft Dynamics CRM 2011/2013 | code reactions

  39. Jishad

    I am using the following code to remove the statuscode option in 2013

    var picklistType = “statuscode”;
    var picklistTypeName = Xrm.Page.ui.controls.get(picklistType);
    picklistTypeName.removeOption(100000000);

    But this code is not working in 2015. Is there is any update for this code?

    Reply
  40. Pingback: JAvascript in Dynamics CRM | DS2171's Blog

  41. Pratima

    can we use onBlur function in CRM 2011.
    Example:If some one fill a field in lower case.It should be change to uppercase on pressing tab.Is it possible in CRM2011?

    Reply

Leave a reply to jadanarendra Cancel reply