CRM JavaScript
CRM JavaScript
CRM JavaScript:
CRM JavaScript is a Client Side Programming which is used to implement custom Business logic From
the Client End.
CRM Entity Properties:
Xrm.Page.data.entity.getEntityName()
Example: var entityName = Xrm.Page.data.entity.getEntityName();
Comments: If we execute this script in Acccount Form events, variable entityName will have the
value “Account”.
Xrm.Page.data.entity.getId()
Example: var recGUID = Xrm.Page.data.entity.getId();
Comments: If we execute this script in Accounts Form events, varuable recGUID will have the
GUID of that particular record.
NOTE: You can specify the maximum length (number of characters) for the field. This must be
a number between 1 and 4000.
2. OptionSet :
OptionSet Properties:
Comments: We use this method to get all option set values in the field which is of type
OptionSet.
Example :
for(i=0;i<Options.length;i++)
alert(Options[i].text);
alert(Options[i].value);
The above script will return the text and value of the optionset “new_region”
Note: To get the optionset text, we need to used “text” property and to get the
optionset value, we need to used “value” property as mentioned in above example.
Get Selected Option Text
Xrm.Page.data.entity.attributes.get(“new_region”).getText();
Comments: We use this method to get the selected option text of particular optionset
“new_region”.
Xrm.Page.data.entity.attributes.get(“new_region”).getValue();
Comments: We use this method to get the selected option value of particular optionset
“new_region”.
Xrm.Page.getAttribute(“new_region”).setValue(parseInt(Value));
Comments: To set the value to optionset, we need to parse the value to integer.
Example: Xrm.Page.getAttribute(“new_region”).setValue(parseInt(1));
3. Two Options:
Comments:We use this method to get the value of the field which is of type Two
Options.
The above script will return either “true” or “false” for the respective options.
Set Two-Options:
Xrm.Page.getAttribute("fieldname").setValue(true);//to set True value
Xrm.Page.getAttribute("fieldname").setValue(false);//to set False value
Comments: We use these method to set the value of the field which is of type Two
Options.
4. WholeNumber :
Xrm.Page.data.entity.attributes.get("fieldname").setValue(123);
Comments: We use this method to set (assign) a value to the field which is of type
WholeNumber. In the above example “fld_name” is the name of the field and we are
assigning 123 to the field “fld_name”. Note we have not used the quotes to set the
value.
NOTE: You can specify the range of values that will be accepted from the overall
minimum (-2,147,483,648) to the overall maximum (+2,147,483,647).
Xrm.Page.data.entity.attributes.get(“fld_name”).getValue();
Comments: We use this method to get the field value which is of type WholeNumber.
In the above example “fld_name” is the name of the field.
Xrm.Page.data.entity.attributes.get("fieldname").setValue(2.345);
Comments: We use this method to set (assign) a value to the field which is of type
WholeNumber. In the above example “fld_name” is the name of the field and we are
assigning 2.345 to the field “fld_name”. Note we have not used the quotes to set the
value.
NOTE: The floating point number is depended on precision Value. You can have from 0
to 5 decimal places, and numbers from -100,000,000,000.00000 to
+100,000,000,000.00000
6. Decimal Number:
Xrm.Page.data.entity.attributes.get(“fld_name”).getValue();
Comments: We use this method to get the field value which is of type WholeNumber.
In the above example “fld_name” is the name of the field.
Xrm.Page.data.entity.attributes.get("fieldname").setValue(2.345);
Comments: We use this method to set (assign) a value to the field which is of type
WholeNumber. In the above example “fld_name” is the name of the field and we are
assigning 2.345 to the field “fld_name”.
NOTE: The Decimal number is depended on precision Value. You can have from 0 to 10
decimal places, and numbers from -100,000,000,000.00000 to +100,000,000,000.00000
7. Currency:
Xrm.Page.data.entity.attributes.get(“fld_name”).getValue();
Comments: We use this method to get the field value which is of type Currency.
In the above example “fld_name” is the name of the field.
Xrm.Page.data.entity.attributes.get("fieldname").setValue(2.345);
Comments: We use this method to set (assign) a value to the field which is of type
Currency. In the above example “fld_name” is the name of the field and we are
assigning 2.345 to the field “fld_name”.
NOTE: You can configure an allowed range of values for the field from -
992,337,203,685,477.0000 to +992,337,203,685,477.0000 (to however many decimal
places the field supports).
Xrm.Page.data.entity.attributes.get(“fld_name”).getValue()
Comments: We use this method to get the field value which is of type (CRM Field Text) text.
In the above example “fld_name” is the name of the field.
Set Value To Text Field:
Xrm.Page.data.entity.attributes.get(“fld_name”).setValue(“First”)
Comments: We use this method to set (assign) a value to the field which is of type (CRM
Field Text) text. In the above example “fld_name” is the name of the field and weare
assigning “First” to the field “fld_name”.
NOTE: You can specify maximum number of characters for the field it can hold, up to a
limit of 100000 (which translates as 200,000 bytes because it is Unicode). When you
display the field on a form, you will be allowed to choose how may lines/rows the control
will occupy (to a maximum of 50).
Xrm.Page.data.entity.attributes.get(fieldname).getValue();
Comments: We use this method to get the full date value which is of type Date and
Time.
Example:
var date = Xrm.Page.data.entity.attributes.get(“new_date”).getValue();
So, here date = Mon Apr 1 00:00:00 UTC+0530 2013
var curr_date = date.getDate(); // it will return 1
var curr_month = date.getMonth(); // it will return 3 , getMonth() considers Jan month
as 0, so we need to add 1 to it.
var curr_year = date.getFullYear(); // it will return 2013
Xrm.Page.data.entity.attributes.get(fieldname).setValue(date);
Where date = Xrm.Page.data.entity.attributes.get(“new_date”).getValue();
Comments: We use this method to set the full date value which is of type Date and
Time.
Example: We can also set the date value literally rather than copying the value from
another date field by using the following script.
10. Lookup:
Xrm.Page.data.entity.attributes.get(“fieldname”).getValue()[0].id;
Comments: We use this method to get the id value which is of type Lookup.
Xrm.Page.data.entity.attributes.get(“fieldname”).getValue()[0].name;
Comments: We use this method to get the name which is of type Lookup.
Xrm.Page.data.entity.attributes.get(“fieldname”).getValue()[0].entityType;
Comments: We use this method to get the Entity Type(i.e Entity Name) which is of type
Lookup.
Example:
var entityType = Xrm.Page.data.entity.attributes.get(“ownerid”).getValue()[0].entityType;
here, we will get “systemuser” because ownerid is the lookup field consists of SystemUser
records .
Field Properties:
Xrm.Page.getAttribute("fieldName").setSubmitMode("always");
Comments: ReadOnly /Disabled fields are not submitted to the database to be saved. So if you
want to save a read only/disabled field you need to set the SubmitMode to be always, which
ensures the value is sent to the database.
Show a Field:
Xrm.Page.ui.controls.get(“fieldname”).setVisible(true);
Comments: We can execute this script to visible the field on the respective form.
Hide a Field:
Xrm.Page.ui.controls.get(“fieldname”).setVisible(false);
Comments: We can execute this script to hide the field on the respective form.
Comments: This is deprecated in CRM . Alternatively we can Disable a field. Best practice is to
use role based form. This will give better performance.
In CRM 4.0, we used the following script.
crmForm.all.fieldname.readOnly = true;
Note: To use crm 4.0 java script we need to enable the HTC compenents option that is
available on personal options customizations tab. But this is not recommended.
Disable a Field:
Xrm.Page.ui.controls.get(“fieldname”).setDisabled(true);
Note: A disabled control show it's value greyed, indicating to the user that they cannot
modify it's contents. To modify the disabled field value, Please refer to Set Submit Mode to
Readonly/Disabled Fields section.
Enable a Field:
Xrm.Page.ui.controls.get(“fieldname”).setDisabled(false);
Comments: We execute the above script to enable the disabled field (fieldname) on the
respective form.
Set Focus:
Xrm.Page.ui.controls.get(“fieldname”).setFocus();
Comments: execute the above script to set the focus on field “fieldname”.
Xrm.Page.getAttribute(“fieldname”).setRequiredLevel(“none”);
Xrm.Page.getAttribute(“fieldname”).setRequiredLevel(“required”);
Xrm.Page.getAttribute(“fieldname”).setRequiredLevel(“recommended”);
Xrm.Page.ui.controls.get(“fieldname”).setLabel(“Label Text”);
Comments: Execute the above script to set the label for the particular fieldname.
Hide A Section:
Hide A Tab:
Xrm.Page.ui.tabs.get("TAB NAME").setVisible(false);
To IFrame:
Note: By Selecting the highlighted check box, We can pass the RecordId,
ObjectType as parameters to the URL of an IFrame.
Xrm.Page.ui.controls.get(“IFrame_name”).setSrc(“URL”);
Comments: The above script is to set Url to an IFrame from Javascript. Where
“IFrame_name” is name of the IFrame.
Note: If we are willing to call ODATA Related JSript file from HTML webresource we
need to add two script files (JQuery.js,JSON.js) like below.
Context. getQueryStringParameters():
If you check the checkbox in the Iframe properties window it will pass id,orgname etc. as
query string parameters.
In the Jscript file we can we can read this using context.getQueryStringParameters()
method.
Reading Querystring Parameters from Jscript file:
Xrm.Page.ui.controls.get(“WebResource Name”).setSrc(“URL”);
Xrm.Page.context.getUserId();
Comments: Returns the GUID value of the SystemUser.id value for the current user.
Xrm.Page.context.getOrgUniqueName();
Xrm.Page.context.getClientUrl();
Comments : getServerUrl() is Deprecated. Use getClientUrl() instead. Returns the base server
URL.
Xrm.Page.context.getUserRoles();
Comments: Returns an array of strings representing the GUID values of each of the security
roles that the user is associated with.
Example: The below function will return the logged-in user security role names
function GetRoles()
{
var context = Xrm.Page.context;
var serverUrl = context.getServerUrl();
var ODATA_ENDPOINT = "/XRMServices//OrganizationData.svc";
// Specify the ODATA entity collection
var ODATA_EntityCollection = "/RoleSet";
var roles = new Array();
roles = Xrm.Page.context.getUserRoles(); //getUserRoles() will return the
logged-in user’s role Guid’s
if (roles != null) {
for (i = 0; i < roles.length; i++)
{
var guid = roles[i];
//Asynchronous AJAX function to Create a CRM record using OData
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: serverUrl + ODATA_ENDPOINT + ODATA_EntityCollection +
"(guid'" + guid + "')",
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) {
//alert("success");
var name = data["d"];
alert(name.Name);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("failure");
}
});
}
}
}
Description:
If we need to remove an option from OptionSet for a specific role we can remove the option
value by using the below code.
Code:
roles = Xrm.Page.context.getUserRoles();
if (roles != null) {
for (i = 0; i < roles.length; i++) {
PickListControl.removeOption(7);
Save Form:
Xrm.Page.data.entity.save();
Save & Close Form:
Xrm.Page.data.entity.save(“saveandclose”);
Close Form:
Xrm.Page.ui.close();
window.location.reload();
window.parent.opener.parent.location.reload();
Description:
In Some cases we need to prevent the form saving by considering some conditions on the form.
In our case the user always need to enter the amount which is greater than 10 if he enters
below 10 the form will not be saved.
Code:
event.returnValue = false;
return false;
document.getElementById("name").style.backgroundColor="red";
Comments: This script is to set the background color of field as shown in below figure.
document.getElementById("name").style.color="yellow";
Comments: This script is to set the font color of field as shown in below figure.
Comments: This script is to set the label color for the field as shown in below figure.
document.getElementById("name_c").style.backgroundColor="red";
Comments: This script is to set the label background color for the field as shown in
below figure.
Set Border color of the field:
document.getElementById("name_d").style.backgroundColor="yellow";
Comments: This script is to set the border color for the field as shown in below figure.
Description:
In Some Cases we need to hide the related entity , previously for choice solutions we hide the
related entity called ‘COPF’ unless until the opportunity probalbility reaches 100 percent.
Code:
document.getElementById("nav_new_opportunity_new_opportunitystage").style.display =
"none";
Description:
Previously we got a requirement that the user need to call a particular dialog from Ribbon
button there we implemented that requirement using the below code snippet.
Code:
function Run() {
var url="https://marvellind.crm5.dynamics.com/cs/dialog/rundialog.aspx?DialogId=
%7b15EEF189-8D9C-4F6E-97C3-3682D9A8BAF2%7d&EntityName=lead&ObjectId=" + Id1;
alert(url);
//window.open(url);
There are 68 different operators that can be used when creating filters in FetchXML.
Some operators that deal with common non-date related evaluations include the following.
Other similar comparison operators include the following.
There are also a number of date evaluation related operators available such as last-fiscal-year, today,
next-year, yesterday, and others.
ODATA:
Description:
Microsoft Dynamics CRM uses the Windows Communication Foundation (WCF) Data Services
framework to provide an endpoint that is a REST-based data service. This endpoint is called
the Organization Data Service.
OData sends and receives data by using either ATOM or JavaScript Object Notation (JSON). ATOM is an
XML-based format usually used for RSS feeds. JSON is a text format that allows for serialization of
JavaScript objects.
Note: It is recommended to use ODATA REST Endpoint instead of SOAP Endpoint in CRM .
IMPORTANT NOTE:
1. We need to add Jquery an Json libraries as jScript Webresources and add it to form libraries.
2. OData Supports only Schema Names for Attributes.For example, For Account Number in Account
Entity we need to use “AccountNumber” but not “accountnumber”.
3. In OData, We need to follow ‘Organization Data Service’ for Entitynames. we can find this service in
SettingsCustomizationDeveloperResources.
For Example,
For Account Entity we need to mention “AccountSet”.
Create Using the REST End Point with JavaScript and JQuery :
Description: The below sample code will creates an account entity record through javascript
and jquery.
SQL Statement: INSERT INTO Account (Name, Telephone1, FAX) VALUES (‘TEST’,’123’,’ 99999’)
function OnLoad() {
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
// Define attribute values for the CRM object you want created
CRMObject.Name = "TEST";
CRMObject.Telephone1 = "123";
CRMObject.Fax = "99999";
datatype: "json",
data: jsonEntity,
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
alert("success");
},
alert("failure");
});
Update Using the REST End Point with JavaScript and JQuery :
Description: The below sample code will Update an account entity record through javascript
and jquery.
SQL Statement: UPDATE account SET Name = ‘TEST Updated’, Telephone1=’123’, Fax=’ 456’
WHERE accountid = ’ 57a4e111-7027-dd11-b452-0003ff9ee217’
function OnLoad() {
// Define attribute values for the CRM object you want created
CRMObject.Telephone1 = “123”;
CRMObject.Fax = “456”;
datatype: “json”,
data: jsonEntity,
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader(“Accept”, “application/json”);
},
alert("success");
},
alert("failure");
}
});
Delete Using the REST End Point with JavaScript and JQuery :
function OnLoad() {
$.ajax({
type: "POST",
datatype: "json",
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
XMLHttpRequest.setRequestHeader("X-HTTP-Method", "DELETE");
},
alert("success");
},
alert("failure");
});
Retreive Using the REST End Point with JavaScript and JQuery :
function OnLoad() {
$.ajax({
type: "GET",
datatype: "json",
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
alert("success");
alert(name.Name);
},
alert("failure");
});
Retreive Multiple Using the REST End Point with JavaScript and JQuery :
function OnLoad() {
$.ajax({
type: "GET",
datatype: "json",
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
alert("success");
alert(data.d.results.length);
alert(accname); }
},
alert("failure");
});
Retreive Multiple with Filter Using the REST End Point with JavaScript and JQuery :
Description: RetreiveMultiple returns is a collection of entity instances based on the specified
query criteria.
Here, In the below sample script we are retreiving the Account entity record details.
SQL Statement: SELECT TOP 1 Name From account WHERE Name = ‘swansolutions’
function OnLoad() {
$.ajax({
type: "GET",
datatype: "json",
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
alert("success");
alert(data.d.results.length);
alert(accname); }
},
alert("failure");
});
Retreive Multiple with Multiple Filters Using the REST End Point with JavaScript and JQuery :
function OnLoad() {
var select =
"$select=Address1_Country,Address1_City,Name&$orderby=Address1_Country,Address1_Cit
y desc&$filter=(Address1_Country ne null) and (Address1_City ne null)";
$.ajax({
type: "GET",
datatype: "json",
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
alert("success");
alert(data.d.results.length);
alert(accname); }
},
alert("failure");
});
Event Modes:
Description:
For Every event in CRM it should have some Event Mode. Based on the Event Mode we can
implement our logic. For Example, if user tries to deactivate the record I can use Event Mode ‘5’
to prevent the deactivation.
Code:
None : 0
Save : 1
SaveAndClose : 2
Delete : 3
Load : 4
Deactivate : 5
Reactivate : 6
Email Send : 7
Email Reply : 8
Email Forward : 9
Kb Submit : 10
Kb Reject : 11
Kb Publish : 12
Kb UnPublish : 13
Kb Rate : 14
Lead Unqualify : 15
Lead Qualify : 16
Quote Accept : 17
Quote CreateOrder : 18
Order ProcessOrder : 19
Opportunity AddRelatedOrder : 21
Opportunity AddRelatedQuote : 22
Opportunity AddRelatedInvoice : 23
Quote CreateRevision : 24
Quote CloseQuote : 25
Order CancelOrder : 26
Invoice Close : 27
Quote GetProducts : 28
Quote Activate : 29
Email ReplyAll : 30
Contract Hold : 31
Contract ReleaseHold : 32
Contract Cancel : 33
Contract Renew : 34
Product ConvertToKit : 35
Product ConvertFromKit : 36
ContractDetail Cancel : 37
Contract Invoice : 38
Contract Clone : 39
Incident Cancel : 40
Email Assign : 41
Change SalesStage : 42
SalesOrder GetProducts : 43
InvoiceGetProducts : 44
TemplateMakeOrgAvailable : 45
TemplateMakeOrgUnavailable : 46
Assign : 47
IncidentAssignToUser : 49
OrderLock : 50
OrderUnlock : 51
InvoiceLock : 52
InvoiceUnlock : 53
ConvertResponse : 54
ReportMakeOrgAvailable : 60
ReportMakeOrgUnavailable : 61
WorkflowAddCheckStep : 62
WorkflowUpdateCondition : 63
WorkflowCreateAction : 64
SendInvite : 65
WorkflowAddElseIfStep : 66
WorkflowAddElseStep : 67
WorkflowDeleteStep : 68
if(event.Mode == 16)
So, just in case, if you don't want which event is triggered, just add the
following line
alert(event.Mode);
Pass QueryString To Link:
Description:
Previously got a requirement that , By clicking the navigation pane of the form we need to show
aspx page with the corresponding record details only.
Solution:
Code:
function PassQryStrToLink() {
document.getElementById(navItems[navItem].getId()).onclick = function () {
pageUrl = encodeURI('http://localhost:49588/CRMOnlineDataEntry/DataEntryForm.aspx?id='+
currentId + '&type=0'); //passing id as querystring
};
}
Calling a Web Service From CRM:
Description:
We can call a webservice from CRM Using javascript. A web service which will converts
the given number into its respective string.
Code:
function Change()
var xmlHttp;
var input=Xrm.Page.getAttribute("new_value").getValue();
xmlHttp.open('POST',
'http://192.168.64.114/Numbers2WordsConversion/Service.asmx/GetWords', false);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-
urlencoded");
xmlHttp.send("number=" + input);
Xrm.Page.getAttribute("new_valueinwords").setValue(exch);