Get OptionSet Text and Value using Javascript

Please follow the below code to get OptionSet Text and Value

function getOptions() {
    var obj = Xrm.Page.getAttribute("provide fieldSchemaName here");
    if (obj != null) {
        //Get OptionSet Text
        alert("OptionSet Text :" + obj.getText());
        //Get OptionSet Value
        alert("OptionSet Value : " + obj.getValue());
    }
}

Please provide your valuable comments on this article.

Advertisements

SetState Request Example Using Javascript

Add the below Functions in Javascript Webresource and be sure to pass correct StateCode and StatusCode for the particular entity.

function callRecordStatus() {
var recordGuid = Xrm.Page.data.entity.getId();
   //StateCode   2 - Disqualified
   //StatusCode 4 - Lost
setRecordStatus ("lead", recordGuid, "2", "4");
}

function setRecordStatus(entitySchemaName, recordGuid, stateCode, statusCode) {
  // create the request
var request = "";
request += "";
request += "";
request += "";
request += "";
request += "";
request += "EntityMoniker";
request += "";
request += "" + recordGuid +"";
request += "" + entitySchemaName + "";
request += "";
request += "";
request += "";
request += "";
request += "State";
request += "";
request += "" + stateCode + "";
request += "";
request += "";
request += "";
request += "Status";
request += "";
request += "" + statusCode + "";
request += "";
request += "";
request += "";
request += "";
request += "SetState";
request += "";
request += "";
request += "";
request += "";
   //send set state request  
$.ajax({
type: "POST",
contentType: "text/xml; charset=utf-8",
datatype: "xml",
url: Xrm.Page.context.getClientUrl() + "/XRMServices/2011/Organization.svc/web",
data: request,
beforeSend: function(XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/xml, text/xml, */*");
XMLHttpRequest.setRequestHeader("SOAPAction",
"http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
},
success: function(data, textStatus, XmlHttpRequest) {
//Add code after changing Status of the record
},

error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
}

Note:
Xrm.Page.context.getClientUrl() – New javascript function in CRM 2013 used to get ServerURL.

Please provide your valuable comments on this article.

REST – Delete Example

Delete:

Syntax: SDK.REST.deleteRecord(id, type, successCallback, errorCallback)

Name Type Description
id String A String representing the GUID value for the record to delete.
type String The Schema Name of the Entity type record to delete.For an Account record, use “Account”
successCallback Function The function that will be passed through and be called by a successful response.
Nothing will be returned to this function.
errorCallback Function The function that will be passed through and be called by a failed response.
This function must accept an Error object as a parameter.

Task: Delete an Existing Account using AccountId.

Solution: Add the below Script in “new_sdkOperations” Webresource and click Ok.

Please do check REST – Retrieve Example for Initial Setup

function deleteAccount() {
    if (confirm("Do you want to delete this account record?")) {
        alert("You chose to delete the account record.");
        SDK.REST.deleteRecord(
            "{312B24BA-7CC1-E311-AAEF-D89D67790688}", //Add Existing Account GUID
            "Account",
            function() {
                alert("The account was deleted.");
            },
            errorHandler
        );
    }
}

function errorHandler(error) {
    alert(error.message);
}

Add OnLoad event in Account Form, Library: new_sdkOperations &function deleteAccount. Save and Publish

REST - Delete Webresource

Output:

REST - Delete Output

Please provide your valuable comments on this article.

REST – Update Example

Update:

Syntax: SDK.REST.updateRecord(id, object, type, successCallback, errorCallback)

Name Type Description
id String A String representing the GUID value for the record to update.
object Object A JavaScript object with properties corresponding to the Schema Names for entity attributes that are valid for update operations.
type String The Schema Name of the Entity type record to retrieve. For an Account record, use “Account”
successCallback Function The function that will be passed through and be called by a successful response.Nothing will be returned to this function.
errorCallback Function The function that will be passed through and be called by a failed response.This function must accept an Error object as a parameter.

Task: Update Phone Number of an Existing Account using AccountId.

Solution: Add the below Script in “new_sdkOperations” Webresource and click Ok.
Please do check REST – Retrieve Example for Initial Setup

function updateAccount() {
var account = {};
account.Telephone1 = "9876543210";
 SDK.REST.updateRecord("{312B24BA-7CC1-E311-AAEF-D89D67790688}", account, "Account", updateSuccessCallback , errorHandler); //Provide Existing Account record GUID
}

function updateSuccessCallback (){
alert("The account record changes were saved");
}

function errorHandler(error) {
alert(error.message);
}

Add OnLoad event in Account Form, Library: new_sdkOperations &function updateAccount. Save and Publish

REST - Update Webresource

Output:

REST - Update Output

Please provide your valuable feedback on this article.

REST – Create Example

Create

Syntax: SDK.REST.createRecord(object, type, successCallback, errorCallback)

Name Type Description
object Object A JavaScript object with properties corresponding to the Schema name of entity attributes that are valid for create operations.
type String The Schema Name of the Entity type record to create.
successCallback Function The function that will be passed through and be called by a successful response. This function can accept the returned record as a parameter.
errorCallback Function The function that will be passed through and be called by a failed response. This function must accept an Error object as a parameter.

Task:Create a Contact Record

Solution: Add the below Script in “new_sdkOperations” Webresource and click Ok.

Please do check REST – Retrieve Example for Initial Setup

function createAccount() {
var account = {};
account.Name = "Arun Potti";
account.Description = "Account was created using SDK.REST.createRecord Method";

 //Set a lookup value
account.PrimaryContactId = {
Id: "FB4F88B0-49B3-E311-9C70-D89D676E8210", //Provide Existing Contact Guid
LogicalName: "contact",
Name: "Maria Campbell (sample)"                          //Provide Existing Contact Name
};

//Set a picklist value
account.PreferredContactMethodCode = {   Value: 2   };

   //Set a money value
account.Revenue = { Value: "2000000.00"   };

   //Set a Boolean value
account.DoNotPhone = true;

  //Add Two Tasks
var today = new Date();
var startDate = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 3);   //Set a date three days in the future.

  //Low Priority Task
var LowPriTask = { Subject: "Low Priority Task", ScheduledStart: startDate, PriorityCode: { Value: 0 } };

//High Priority Task
var HighPriTask = { Subject: "High Priority Task", ScheduledStart: startDate, PriorityCode: { Value: 2 } };      account.Account_Tasks = [LowPriTask, HighPriTask];

//Create the Account

SDK.REST.createRecord(account, "Account", getAccountDetails, errorHandler);
}

function getAccountDetails(account) {
alert("Account Name : " + account.Name + "\nAccount GUId : " + account.AccountId);
}

function errorHandler(error) { alert(error.message); }

Add OnLoad event in Account Form, Library: new_sdkOperations &function createAccount. Save and Publish

REST - Create Webresource Output

Output:

REST - Create Output

Please provide your valuable comments on this article.

REST – Retrieve Multiple Example

Retrieve Multiple

Syntax: SDK.REST.retrieveMultipleRecords(type, options, successCallback, errorCallback, OnComplete)

Name Type Description
type String The Schema Name of the Entity type record to retrieve.
options String A String that represents the OData System Query Options to control the data returned.
successCallback Function The function that will be passed through and be called for each page of records returned.
This example uses the retrieveContactsCallBack function.
errorCallback Function The function that will be passed through and be called by a failed response.
This example uses the errorCallBack function.
OnComplete Function The function that will be called when all the requested records have been returned.
This example uses the contactsRetrieveComplete function.

Task:  Retrieve all Contacts contains MobilePhone data
Solution: Add the below Script in “new_sdkOperations” Webresource and click Ok.

Please do check REST – Retrieve for Initial Setup.

function retrieveMultipleContacts() {
var options = "$select=FullName,MobilePhone&$filter=MobilePhone ne null"; //Write your own Query to get Records
SDK.REST.retrieveMultipleRecords("Contact", options, retrieveContactsCallBack, errorCallBack, contactsRetrieveComplete);
}

function retrieveContactsCallBack(retrievedContacts) {
var outputString = "";
outputString = "FullName\t\t\tMobile Phone\n";
outputString = outputString + "--------------------------------------------------\n";
for (var i = 0; i < retrievedContacts.length; i++) {
outputString = outputString + retrievedContacts[i].FullName + " \t " + retrievedContacts[i].MobilePhone + "\n";
}
alert(outputString);
}

function errorCallBack(error) {
alert(error.message);
}

// This function is called after all the records have been returned
function contactsRetrieveComplete() {
}

Add OnLoad event in Contact Form, Library: new_sdkOperations & function retrieveMultipleContacts. Save and Publish

Image

Output:
Open any Contact Record to see the below output,

Image

Please provide your valuable comments on this article.

REST – Retrieve Example

REST CRUD (Create, Read, Update and Delete) Operations:

Initial Setup:

Download the Latest SDK.

For CRUD Operations, get the following Script files from the path

SDK\SampleCode\JS\RESTEndpoint\JavaScriptRESTDataOperations\JavaScriptRESTDataOperations\Scripts

Initial Setup

Create two JScript Web Resources

SDK Rest Webresource

Create a JScript Web Resource for CRUD Operations,

SDK Operations JScript

Retrieve Example:

Syntax: SDK.REST.retrieveRecord(id, type, select, expand, successCallback, errorCallback) 

Name Type Description
id String A String representing the GUID value for the record to retrieve.
type String The Schema Name of the Entity type record to retrieve.
select String A String representing the $select OData System Query Option to control which attributes will be returned. This is a comma separated list of Attribute names that are valid for retrieve.
If null all properties for the record will be returned
expand String A String representing the $expand OData System Query Option value to control which related records are also returned. This is a comma separated list of up to 6 entity relationship names
If null no expanded related records will be returned.
successCallback Function The function that will be passed through and be called by a successful response.
This function must accept the returned record as a parameter.
errorCallback Function The function that will be passed through and be called by a failed response.
This function must accept an Error object as a parameter.

 Task:Get the Contact details based on Contact Guid using Retrieve Method

Solution: Add the below Script in “new_sdkOperations” Webresource for Retrieving Contact details based on “ContactId”,

function retrieveContact(ContactId) {
SDK.REST.retrieveRecord(ContactId, "Contact", null, null, getDetails, errorHandler);
}

function getDetails(contact) {
alert("Full Name : "+ contact.FullName + "\n" +
"Company Name : " + contact.ParentCustomerId.Name + "\n" +
"Guid : " + contact.ContactId +"\n" +
"Preferred Method of Contact : " + contact.PreferredContactMethodCode.Value +"\n" +
"Bulk Email : " + contact.DoNotBulkEMail +"\n"+
"Birthday : " + contact.BirthDate
);
}

function errorHandler(error) {
alert(error.message);
}

Save and Publish the Web Resource “new_sdkOperations”.

Add the 3 Web Resources in Contact Entity as follows,

Webresources on Contact Form

Add OnLoad event, Library: new_sdkOperations &function retrieveContact

Attach Onload Event

Pass the Existing Contact Guid as a Parameter to test the function,

Pass Contact Parameter to Form

Save and Publish the entity. Open any record to get the below alert.

Final Output

Please provide your valuable comments on this article.