Friday, 13 November 2015

JAVASCRIPT REFERENCE

JAVASCRIPT REFERENCE

33.  Refresh a Sub-Grid:
1
2
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.
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);
}
35.  Pop an existing CRM record (new approach):
1
2
3
4
5
6
7
8
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.
01
02
03
04
05
06
07
08
09
10
11
12
//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):
1
2
3
function PopNewCase() {
    Xrm.Utility.openEntityForm("incident")
}
38.  Pop a new CRM record with default values (new approach):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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”
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//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.
01
02
03
04
05
06
07
08
09
10
11
12
13
function LaunchDialog(sLeadID) {
    var DialogGUID = "128CEEDC-2763-4FA9-AB89-35BBB7D5517D";
    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/
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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:
1
window.document.getElementById('new_existingcase').click();
43.  Pop a Web Resource (new approach):
1
2
3
function PopWebResource() {
    Xrm.Utility.openWebResource("new_Hello");
}
44. Using a SWITCH statement
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
1
2
3
4
5
6
7
8
9
10
11
12
13
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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:
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!).

No comments:

Post a Comment

Note: only a member of this blog may post a comment.