You are on page 1of 35

CONTENTS

1) CRM Entity Properties


2) Get & Set Values to Field
3) Get & Set Values to Lookup
4) OptionsSet Properties
5) Field Properties
6) To set URL for IFrames/WebResource
7) Get “Current User” & “Organization” Details
8) Form Saving From Code behind
9) ODATA
10) Create Using the REST End Point with JavaScript and JQuery
11) Update Using the REST End Point with JavaScript and JQuery
12) Delete Using the REST End Point with JavaScript and JQuery
13) Retreive Using the REST End Point with JavaScript and JQuery
14) Retreive Multiple Using the REST End Point with JavaScript and JQuery
15) Retreive Multiple with Filter Using the REST End Point with JavaScript and JQuery
16) Retreive Multiple with Multiple Filters Using the REST End Point with JavaScript and JQuery
17) Event Modes
18) Prevent Form Save
19) Hide Related Entity
20) Call Dialog From Ribbon
21) Set Colors to fields on form using JavaScript :
22) Hide OptionSet Value Based On Security Role
23) Pass QueryString To Link
24) Hide A Section
25) Hide A Tab
26) Calling Webservice from CRM

CRM JavaScript:

CRM JavaScript is a Client Side Programming which is used to implement custom Business logic From
the Client End.
CRM Entity Properties:

 Get Entity Name:

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”.

 Get Record GUID:

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.

 Get CRM Form Type:

var type = Xrm.Page.ui.getFormType();


Example:
Xrm.Page.ui .getFromType() - function returns integer value for different Form states
0 - undefined
1 - Create
2 - Update
3 - Read Only
4 - Disabled
5 - Quick Create (Deprecated)
6 - Bulk Edit

Get & Set Values to Field:

Microsoft Dynamics CRM forms consists of 10 datatypes.

1. Single Line of Text


2. OptionSet
3. Two Options
4. WholeNumber
5. Floating Point Number
6. Decimal Number
7. Currency
8. Multiple Lines of Text
9. Date and Time
10. Lookup
Now, we are going to see how to Get and Set Values to above mentioned datatypes using javascript Xrm
coding.

1. Single Lines of Text :

 Get Value From Text Field:


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 the maximum length (number of characters) for the field. This must be
a number between 1 and 4000.

2. OptionSet :

OptionSet Properties:

 Get All Options:


Xrm.Page.data.entity.attributes.get(“fieldname”).getOptions();

Comments: We use this method to get all option set values in the field which is of type
OptionSet.

Example :

var options = Xrm.Page.data.entity.attributes.get("new_region").getOptions();

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”.

 Get Selected Option Value

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”.

 Set OptionSet Value

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:

 Get Two-Options Selected value:


Xrm.Page.getAttribute("fieldname").getValue();

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 :

 Get Value From WholeNumber Field:


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.

 Set Value To WholeNumber Field:

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).

5. Floating Point Number:

 Get Value From Floating point Field:

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.

 Set Value To Floating point 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:

 Get Value From Decimal Field:

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.

 Set Value To Decimal 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:

 Get Value From Currency Field:

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.

 Set Value To Decimal 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).

8. Multiple Lines of Text:

 Get Value From Text Field:

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).

9. Date and Time:

 Get Full Details From Date time Field:

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

 Set Date to Date Time field:

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.

var date = new Date();


date.setDate(5);
var month = 2-1; //SetMonth() considers Jan month as 0, so we need to subtract 1.
For February it is 1. So, I Subtract 1 from 2
date.setMonth(month);
date.setFullYear(2013);
Xrm.Page.data.entity.attributes.get("new_date").setValue(date);

10. Lookup:

Get & Set Values to Lookup:

 Get GUID of Selected From Lookup Field:

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.

 Get Name of Selected From Lookup Field:

Xrm.Page.data.entity.attributes.get(“fieldname”).getValue()[0].name;

Comments: We use this method to get the name which is of type Lookup.

 Get EntityType from Lookup field :

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 .

 Set Value to Lookup Field:

var lookUpValue = new Array();


lookUpValue[0] = new Object();
lookUpValue[0].id = idValue;
lookUpValue[0].name = textValue;
lookUpValue[0].entityType =typeValue;
Xrm.Page.getAttribute(“fieldname”).setValue(lookUpValue);
Comments: We use this method to set the record to the “fieldname” which is of type
Lookup.

Field Properties:

 Set Submit Mode to Readonly/Disabled Fields:

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.

 Set Field to readOnly:

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”.

 Set Field Requirement Level:

Xrm.Page.getAttribute(“fieldname”).setRequiredLevel(“none”);
Xrm.Page.getAttribute(“fieldname”).setRequiredLevel(“required”);
Xrm.Page.getAttribute(“fieldname”).setRequiredLevel(“recommended”);

 Set Label For the Control:

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:

Xrm.Page.ui.tabs.get("TAB NAME").sections.get("SECTION NAME").setVisible(false);

Hide A Tab:

Xrm.Page.ui.tabs.get("TAB NAME").setVisible(false);

To set URL for IFrames/WebResource:

 To IFrame:

We can set the URL to Iframe in two types.


a. Through the Provided Customization in CRM:

Follow the below steps to Create an IFrame.


1. Goto Customizations.
2. Open Entity Form.
3. Insert IFrame to any section.
Here, In the above window itself we can directly set the URL.

Note: By Selecting the highlighted check box, We can pass the RecordId,
ObjectType as parameters to the URL of an IFrame.

b. Override the IFrame URL Through Javascript:

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.

We can also add the QueryString Parameters to IFrame Url as below.


Example: If we need to send record id to IFrame url as Querystring Parameter

var Recid = “100”


var url = “www.oneindia.com/Customers.aspx?Recordid= Recid”
Xrm.Page.ui.controls.get(“IFrame_name”).setSrc(“url”);

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.

<script type="text/javascript" src="new_JQuery"></script>


<script type="text/javascript" src="new_Json"></script>

If we want to access context information from HTML Webresource we need to add


another script file called “ClientGlobalContext.js.aspx”.

<script type="text/javascript" src=" ClientGlobalContext.js.aspx"></script>

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:

var context = Xrm.Page.context;


var newArray = context.getQueryStringParameters();
var guid = newArray.id; //To Read GUID
var orgname = newArray.orgname; //To Read Organization Name
var orglcid = newArray.orglcid; //To Read Organization LCID (Lang. Pack ID)
var type = newArray.type; //To Read Type Code
var typename = newArray.typename; //To Read Entity Name
var userlcid = newArray.userlcid; //To Read User LCID (User Lang.Pack ID)
 To WebResource:

Xrm.Page.ui.controls.get(“WebResource Name”).setSrc(“URL”);

Get “Current User” & “Organization” Details:

 Get Current User GUID:

Xrm.Page.context.getUserId();

Comments: Returns the GUID value of the SystemUser.id value for the current user.

 Get Organization Name:

Xrm.Page.context.getOrgUniqueName();

Comments: Returns the unique text value of the organizations name.

 Get Server URL:

Xrm.Page.context.getServerUrl(); //This is Deprecated.

Xrm.Page.context.getClientUrl();

Comments : getServerUrl() is Deprecated. Use getClientUrl() instead. Returns the base server
URL.

 Get Role IDs of Current User:

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

Hide OptionSet Value Based On Security Role:

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

var roles = new Array();

roles = Xrm.Page.context.getUserRoles();

if (roles != null) {
for (i = 0; i < roles.length; i++) {

if (roles[i] == “5F6F1B88-D261-E211-A12F-D8D3855B15DA”)//roleid hard coded here

var PickListControl = Xrm.Page.getControl("my_stage");

// Provide the value of the Optionset item need to be hide

PickListControl.removeOption(7);

Form Saving From Java Script:

 Save Form:
Xrm.Page.data.entity.save();
 Save & Close Form:
Xrm.Page.data.entity.save(“saveandclose”);
 Close Form:
Xrm.Page.ui.close();

How to Reload a Form:

window.location.reload();

Note: We use this script to refresh the current form.

How to Reload a Parent Form:

window.parent.opener.parent.location.reload();

Note: We need to use this script on child form on save event.

Prevent Form Save:

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

if(crmForm.all.new_quantityinhand.DataValue < 10)


{

alert('Enter Greater Than 10');

event.returnValue = false;

return false;

Set Colors to fields on form using JavaScript :

 Set field background color:

document.getElementById("name").style.backgroundColor="red";

Comments: This script is to set the background color of field as shown in below figure.

 Set field font color:

document.getElementById("name").style.color="yellow";

Comments: This script is to set the font color of field as shown in below figure.

 Set Label color of the field :


document.getElementById("name_c").style.color="red";

Comments: This script is to set the label color for the field as shown in below figure.

 Set Label Background color of the field

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.

Hide Related Entity:

 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";

Call Dialog From Ribbon:

 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 Id1 = crmForm.ObjectId;

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, "", "status=no,scrollbars=no,toolbars=no,menubar=no,location=no");

//window.open(url);

Fetch XML Query Operators:

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
SettingsCustomizationDeveloperResources.

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’)

 Sample Code to Create Record:


// JScript source code

function OnLoad() {

var context = Xrm.Page.context;

var serverUrl = context.getServerUrl();

var ODATA_ENDPOINT = "/XRMServices//OrganizationData.svc";

var CRMObject = new Object();

/////////////////////////////////////////////////////////////

// Specify the ODATA entity collection

var ODATA_EntityCollection = "/AccountSet"; //pl refer to

/////////////////////////////////////////////////////////////

// Define attribute values for the CRM object you want created

CRMObject.Name = "TEST";

CRMObject.Telephone1 = "123";

CRMObject.Fax = "99999";

//Parse the entity object into JSON

var jsonEntity = window.JSON.stringify(CRMObject);

//Asynchronous AJAX function to Create a CRM record using OData

$.ajax({ type: "POST",

contentType: "application/json; charset=utf-8",

datatype: "json",

url: serverUrl + ODATA_ENDPOINT + ODATA_EntityCollection,

data: jsonEntity,

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 NewCRMRecordCreated = data["d"];

alert("CRM GUID created: " + NewCRMRecordCreated.AccountId);

},

error: function (XMLHttpRequest, textStatus, errorThrown) {

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’

 Sample Code to Update Records:

// Jscript source code

function OnLoad() {

var context = Xrm.Page.context;

var serverUrl = context.getServerUrl();

var guid = Xrm.Page.data.entity.getId();

var name = Xrm.Page.getAttribute(“name”).getValue();

var ODATA_ENDPOINT = “/XRMServices//OrganizationData.svc”;

var CRMObject = new Object();

// Specify the ODATA entity collection

var ODATA_EntityCollection = “/AccountSet”;


/////////////////////////////////////////////////////////////

// Define attribute values for the CRM object you want created

CRMObject.Name = “TEST Updated”;

CRMObject.Telephone1 = “123”;

CRMObject.Fax = “456”;

//Parse the entity object into JSON

var jsonEntity = window.JSON.stringify(CRMObject);

//Asynchronous AJAX function to Create a CRM record using OData

$.ajax({ type: “POST”,

contentType: “application/json; charset=utf-8”,

datatype: “json”,

url: serverUrl + ODATA_ENDPOINT + ODATA_EntityCollection + “(guid’” + guid + “’)”,

data: jsonEntity,

beforeSend: function (XMLHttpRequest) {

//Specifying this header ensures that the results will be returned as JSON.

XMLHttpRequest.setRequestHeader(“Accept”, “application/json”);

XMLHttpRequest.setRequestHeader(“X-HTTP-Method”, “MERGE”);//for update only we


need to add this script.

},

success: function (data, textStatus, XmlHttpRequest) {

alert("success");

var value = Xrm.Page.getAttribute("name").getValue();

alert("CRM Record Name"+name+"is updated to: " +value);

},

error: function (XMLHttpRequest, textStatus, errorThrown) {

alert("failure");
}

});

Delete Using the REST End Point with JavaScript and JQuery :

 Description: Deletes an entity instance of account Record with accountid {57a4e111-7027-


dd11-b452-0003ff9ee217} from any other entity.

 SQL Statement: DELETE FROM account WHERE accountid = ‘57a4e111-7027-dd11-b452-


0003ff9ee217’

 Sample Code to Delete a Account Record:

// JScript source code

function OnLoad() {

var context = Xrm.Page.context;

var serverUrl = context.getServerUrl();

var guid = Xrm.Page.data.entity.getId();

var ODATA_ENDPOINT = "/XRMServices//OrganizationData.svc";

// Specify the ODATA entity collection

var ODATA_EntityCollection = "/AccountSet";

//Asynchronous AJAX function to Create a CRM record using OData

$.ajax({

type: "POST",

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");
XMLHttpRequest.setRequestHeader("X-HTTP-Method", "DELETE");

},

success: function (data, textStatus, XmlHttpRequest) {

alert("success");

},

error: function (XMLHttpRequest, textStatus, errorThrown) {

alert("failure");

});

Retreive Using the REST End Point with JavaScript and JQuery :

 Description: To Retrieve an entity instance using the specified ID.


Here, In the below sample script we are retreiving the specific Account record details.

 SQL Statement: SELECT Name From account WHERE accountid = ‘57a4e111-7027-dd11-b452-


0003ff9ee217’

 Sample Code to Retreive a Account Record:

// JScript source code

function OnLoad() {

var context = Xrm.Page.context;

var serverUrl = context.getServerUrl();

var guid = Xrm.Page.data.entity.getId();

var ODATA_ENDPOINT = "/XRMServices//OrganizationData.svc";

// Specify the ODATA entity collection

var ODATA_EntityCollection = "/AccountSet";

//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");

});

Retreive Multiple Using the REST End Point with JavaScript and JQuery :

// JScript source code

function OnLoad() {

var context = Xrm.Page.context;

var serverUrl = context.getServerUrl();

// var guid = Xrm.Page.data.entity.getId();

var ODATA_ENDPOINT = "/XRMServices//OrganizationData.svc";


// Specify the ODATA entity collection

var ODATA_EntityCollection = "/AccountSet";

//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,

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");

alert(data.d.results.length);

for( i=0; i< data.d.results.length; i++) {

var oneEntity = data.d.results[i];

var accname = oneEntity.Name;

alert(accname); }

},

error: function (XMLHttpRequest, textStatus, errorThrown) {

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’

 Sample Code to Retreive Multiple Records:

// JScript source code

function OnLoad() {

var context = Xrm.Page.context;

var serverUrl = context.getServerUrl();

var select = "$select=Name&$top=1&$filter=Name eq 'swansolutions'";

// var guid = Xrm.Page.data.entity.getId();

var ODATA_ENDPOINT = "/XRMServices//OrganizationData.svc";

// Specify the ODATA entity collection

var ODATA_EntityCollection = "/AccountSet";

//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+"?"+select ,

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");
alert(data.d.results.length);

for( i=0; i< data.d.results.length; i++) {

var oneEntity = data.d.results[i];

var accname = oneEntity.Name;

alert(accname); }

},

error: function (XMLHttpRequest, textStatus, errorThrown) {

alert("failure");

});

Retreive Multiple with Multiple Filters 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(AccountSet) record
details.

 SQL Statement: SELECT Address1_Country,Address1_City,Name From account WHERE


Address1_Country =’’ and Address1_City=’’ ORDER BY Address1_Country,Address1_City

 Sample Code to Retreive Multiple Records with Filters:

// JScript source code

function OnLoad() {

var context = Xrm.Page.context;

var serverUrl = context.getServerUrl();

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)";

// var guid = Xrm.Page.data.entity.getId();

var ODATA_ENDPOINT = "/XRMServices//OrganizationData.svc";


// Specify the ODATA entity collection

var ODATA_EntityCollection = "/AccountSet";

//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+"?"+select ,

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");

alert(data.d.results.length);

for( i=0; i< data.d.results.length; i++) {

var oneEntity = data.d.results[i];

var accname = oneEntity.Name;

alert(accname); }

},

error: function (XMLHttpRequest, textStatus, errorThrown) {

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

You can then use it like :

if(event.Mode == 16)

// Check whatever you want

So, just in case, if you don't want which event is triggered, just add the

following line

in the onSave event of the form:

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:

1. Setting the .ASPX Page on Sitemap Subarea in Entity Form.


2. we need to send a particular record GUID to .aspx page on navigation item click. There we
implemented below code in order to pass the GUID as a Query String Parameter to .aspx
page.

 Code:

function PassQryStrToLink() {

var navItems = Xrm.Page.ui.navigation.items.get();//Returns all the navigation items from form

for (var navItem in navItems) {

if (navItems[navItem].getLabel() == "Opportunity") { //here Opportunity is the label name of


navigation item

var pageUrl = "";

document.getElementById(navItems[navItem].getId()).onclick = function () {

var currentId = Xrm.Page.data.entity.getId(); //returns current record guid

pageUrl = encodeURI('http://localhost:49588/CRMOnlineDataEntry/DataEntryForm.aspx?id='+
currentId + '&type=0'); //passing id as querystring

loadIsvArea(this,Mscrm.CrmUri.create(pageUrl),false, new Sys.UI.DomEvent(event)); //loading


the ISV Area with the aspx page by posting the pageurlalert(currentId);

};

}
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 = new ActiveXObject("Microsoft.XMLHTTP");

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

var xmlDoc = xmlHttp.responseXML;

var responseElement = xmlDoc.getElementsByTagName("string")[0];

var exch = responseElement.firstChild.nodeValue;

Xrm.Page.getAttribute("new_valueinwords").setValue(exch);

You might also like