Pages

Wednesday, 17 April 2013

JQuery code to Create , Retrieve , Update , Delete entity record in CRM 2011

In this article , I am going to explain how to create , retrieve , update , delete entity record in CRM 2011

First need to add these three javascript files as webresource in CRM
jquery1.4.1.min.js
json2.js
SDK.JQuery.js

these files are in SDK under Script folder (sdk\samplecode\js\restendpoint\jqueryrestdataoperations\jqueryrestdataoperations\scripts)


var primaryContact = null;

Code to create Account Entity record
function createAccount() {
    getFirstContactToBePrimaryContact();
    var account = {};
    account.Name = "Test Account Name";
    account.Description = "This account was created by the JQueryRESTDataOperations sample.";
    if (primaryContact != null) {
        //Set a lookup value
        account.PrimaryContactId = { Id: primaryContact.ContactId, LogicalName: "contact", Name: primaryContact.FullName };
    }
    //Set a picklist value
    account.PreferredContactMethodCode = { Value: 2 };
    //Set a money value
    account.Revenue = { Value: "2000000.00" };
    //Set a Boolean value
    account.DoNotPhone = true;
    //Create the Account
    SDK.JQuery.createRecord(
     account,
     "Account",
     function (account) {
         alert("The account named \"" + account.Name + "\" was created with the AccountId : \"" + account.AccountId + "\".");
         retrieveAccount(account.AccountId)
     },
     errorHandler
   );

}


Code to retrieve Account Entity record
function retrieveAccount(AccountId) {
    SDK.JQuery.retrieveRecord(
     AccountId,
     "Account",
     null, null,
     function (account) {
         alert("Retrieved the account named \"" + account.Name + "\". This account was created on : \"" + account.CreatedOn + "\".");
         updateAccount(AccountId);
     },
     errorHandler
   );
}

Code to update Account Entity record
function updateAccount(AccountId) {
    var account = {};
    account.Name = "Updated Account Name";
    account.Address1_AddressTypeCode = { Value: 3 };
    account.Address1_City = "Sammamish";
    account.Address1_Line1 = "123 Maple St.";
    account.Address1_PostalCode = "98074";
    account.Address1_StateOrProvince = "WA";
    account.EMailAddress1 = "someone@microsoft.com";
    SDK.JQuery.updateRecord(
     AccountId,
     account,
     "Account",
     function () {
         alert("The account record changes were saved");
         deleteAccount(AccountId);
     },
     errorHandler
   );
}

Code to delete Account Entity record
function deleteAccount(AccountId) {
    if (confirm("Do you want to delete this account record?")) {
        SDK.JQuery.deleteRecord(
       AccountId,
       "Account",
       function () {
           alert("The account was deleted.");
           enableResetButton();
       },
       errorHandler
     );
    }
}

Code to retrieve muliple contact Entity records
function getFirstContactToBePrimaryContact() {
    SDK.JQuery.retrieveMultipleRecords(
     "Contact",
     "$select=ContactId,FullName&$top=1",
     function (results) {
         var firstResult = results[0];
         if (firstResult != null) {
             primaryContact = results[0];
         }
     },
     errorHandler,
     function () {
         //OnComplete handler
     }
   );
}

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


JQuery asynchronous and synchronous retrieve using REST in CRM 2011

In this article , i am going to explain how to make asynchronous and synchronous call using javascript in CRM 2011

first you need to add JQuery file on form as webresource and if you want to run javascript code asynchronous  then make async attribute value true else false in below code


function Retrieve() {
    var jSonArray = new Array();

    if (Xrm.Page.getAttribute("account").getValue() != null) {
        //acount guid no
        var studentid = Xrm.Page.data.entity.attributes.get("account").getValue()[0].id;

        var filter = "$select=name&$filter=accountid eq guid'" + studentid + "'"
        var entityset = 'account';

        var pagecontext = Xrm.Page.context;
        var serverUrl = pagecontext.getServerUrl();
        if (serverUrl.match(/\/$/)) {
            serverUrl = serverUrl.substring(0, serverUrl.length - 1);
        }
        var odataSelect = serverUrl + "/xrmservices/2011/OrganizationData.svc/" + entityset + "Set?" + filter;

        //asynchronous call -> async: true
        //synchronous call -> async: true
        $.ajax({
            type: "GET",
            async: false,
            contentType: "application/json; charset=utf-8",
            datatype: "json",
            url: odataSelect,
            beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
            success: function (data, textStatus, XmlHttpRequest) {
                jSonArray.push(data.d);
                onSaveSuccess(jSonArray);
            },
            error: function (XmlHttpRequest, textStatus, errorThrown) { alert('OData Select Failed: ' + odataSelect); }
        });
    }

}

function onSaveSuccess(jSonArray) {
    if (jSonArray != null && jSonArray[0].results.length > 0) {
        var accountname = jSonArray[0].results[0].name;
    }
}

Wednesday, 6 March 2013

Execute workflow using javascript in CRM 2011

In this article, i am going to explain how to execute workflow using javascript code. You only need to assign your workflow id to "workflowId" variable


function RunWorkflow() {
    var _return = window.confirm('Are you want to execute workflow.');
    if (_return) {
        var url = Xrm.Page.context.getServerUrl();
        var entityId = Xrm.Page.data.entity.getId();
        var workflowId = '541B45C9-3F88-4448-9690-2D4A365C3172';
        var OrgServicePath = "/XRMServices/2011/Organization.svc/web";
        url = url + OrgServicePath;
        var request;
        request = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
                      "<s:Body>" +
                        "<Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" +
                          "<request i:type=\"b:ExecuteWorkflowRequest\" xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\" xmlns:b=\"http://schemas.microsoft.com/crm/2011/Contracts\">" +
                            "<a:Parameters xmlns:c=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">" +
                              "<a:KeyValuePairOfstringanyType>" +
                                "<c:key>EntityId</c:key>" +
                                "<c:value i:type=\"d:guid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/\">" + entityId + "</c:value>" +
                              "</a:KeyValuePairOfstringanyType>" +
                              "<a:KeyValuePairOfstringanyType>" +
                                "<c:key>WorkflowId</c:key>" +
                                "<c:value i:type=\"d:guid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/\">" + workflowId + "</c:value>" +
                              "</a:KeyValuePairOfstringanyType>" +
                            "</a:Parameters>" +
                            "<a:RequestId i:nil=\"true\" />" +
                            "<a:RequestName>ExecuteWorkflow</a:RequestName>" +
                          "</request>" +
                        "</Execute>" +
                      "</s:Body>" +
                    "</s:Envelope>";

        var req = new XMLHttpRequest();
        req.open("POST", url, true)
        // Responses will return XML. It isn't possible to return JSON.
        req.setRequestHeader("Accept", "application/xml, text/xml, */*");
        req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
        req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
        req.onreadystatechange = function () { assignResponse(req); };
        req.send(request);
    }
}

function assignResponse(req) {
    if (req.readyState == 4) {
        if (req.status == 200) {
            alert('successfully executed the workflow');
        }
    }
}

Expand only selected tab using java script in CRM 2011 (After RU12)


In this article i am going to explaining how to expand only selected tab from left side navigation links and other tab will collapsed

you need to call this "SetTabonClick" javascript function on your form onload event to auto expand and collapse tabs from left side navigation links


ffunction SetTabonClick() {
    var tabs = Xrm.Page.ui.tabs.get();
    for (var i in tabs) {
        var tab = tabs[i];
        var tabName = tab.getName();
        var tabindex = 'tab' + i;
        var tabindexTab = 'tab' + i + 'Tab';
        toggleTabDisplayState(tabName, tabindex, tabindexTab);
    }
}
function toggleTabDisplayState(tabName, tabindex,tabindexTab) {
    var link = document.getElementById(tabindexTab); //tab1Tab
    link.onclick = function () {
    Mscrm.Details.loadArea(this, 'areaForm');$find('crmForm').GetTab($get(tabindex, $get('crmForm')), true);
     
        var tabs = Xrm.Page.ui.tabs.get();
        for (var i in tabs) {
            var tab = tabs[i];
            if (tab.getName() == tabName) {
                tab.setDisplayState("expanded");
            }
            else {
                tab.setDisplayState("collapsed");
            }
        }
    }
}

Friday, 4 January 2013

Change Default Calendar View in CRM 2011

In this article , I am going to explain how to change Default Calendar View "Day" to "Monthly" or Weekly"

In Personal Setting Option Go to File -> Options-> Acvivities Tab-> Default Calendar View




Expand only selected tab using java script in CRM 2011 (Without RU12)

In this article i am going to explaining how to expand only selected tab from left side navigation links and other tab will collapsed

you need to call this "SetTabonClick" javascript function on your form onload event to auto expand and collapse tabs from left side navigation links


function SetTabonClick() {
var tabs = Xrm.Page.ui.tabs.get();
    for (var i in tabs) {
        var tab = tabs[i];
        var tabName = tab.getName();
        var tabindex = 'tab' + i;
        var tabindexTab = 'tab' + i + 'Tab';
        toggleTabDisplayState(tabName, tabindex, tabindexTab);
    }
}

function toggleTabDisplayState(tabName, tabindex,tabindexTab) {
    var link = document.getElementById(tabindexTab); //tab1Tab
    link.onclick = function () {
        loadArea('areaForm');
        crmForm.GetTab($get(tabindex, crmForm), true); //tab1

        var tabs = Xrm.Page.ui.tabs.get();
        for (var i in tabs) {
            var tab = tabs[i];
            if (tab.getName() == tabName) {
                tab.setDisplayState("expanded");
            }
            else {
                tab.setDisplayState("collapsed");
            }
        }
    }
}