Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

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

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



Friday, 10 August 2012

Soap XML RetrieveMultiple using javascript in CRM 2011


In this article , I am going to explain how to use Soap XML Retrieve web service
http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple

In this javascript code i am fetching all contact have same value as custom attribute value

Soap XML retrievemutliple
var contactname = Xrm.Page.getAttribute("new_contact").getValue();
var authenticationHeader = GenerateAuthenticationHeader();
if (contactname != null && contactname != "undefined") {
    var Accountxml = "" + "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
    "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
    authenticationHeader +
    "  <soap:Body>" +
    "    <RetrieveMultiple xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
    "      <query xmlns:q1='http://schemas.microsoft.com/crm/2006/Query' xsi:type='q1:QueryExpression\'>" +
    "        <q1:EntityName>contact</q1:EntityName>" +

    "        <q1:ColumnSet xsi:type=\"q1:ColumnSet\">" +
    "          <q1:Attributes>" +
    "            <q1:Attribute>address1_city</q1:Attribute>" +
    "            <q1:Attribute>address1_stateorprovince</q1:Attribute>" +
    "          </q1:Attributes>" +
    "        </q1:ColumnSet>" +

    "        <q1:Distinct>false</q1:Distinct>" +

    "        <q1:PageInfo>" +
    "          <q1:PageNumber>1</q1:PageNumber>" +
    "          <q1:Count>1</q1:Count>" +
    "        </q1:PageInfo>" +

    "        <q1:Criteria>" +
    "          <q1:FilterOperator>And</q1:FilterOperator>" +
    "          <q1:Conditions>" +
    "            <q1:Condition>" +
    "              <q1:AttributeName>firstname</q1:AttributeName>" +
    "              <q1:Operator>Equal</q1:Operator>" +
    "              <q1:Values>" +
    "                <q1:Value xsi:type=\"xsd:string\">" + contactname + "</q1:Value>" +
    "              </q1:Values>" +
    "            </q1:Condition>" +
    "          </q1:Conditions>" +
    "        </q1:Criteria>" +
    "      </query>" +
    "    </RetrieveMultiple>" +
    "  </soap:Body>" +
    "</soap:Envelope>" +
    "";
    // Create an instance of an XMLHTTP object.
    var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
    xmlHttpRequest.Open(
            "POST",
            "/mscrmservices/2007/CrmService.asmx",
            false
            );

    xmlHttpRequest.setRequestHeader(
            "SOAPAction",
            "http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple"
            );

    xmlHttpRequest.setRequestHeader(
            "Content-Type", "text/xml; charset=utf-8"
            );

    xmlHttpRequest.setRequestHeader(
            "Content-Length", Accountxml.length
            );

    // Send the XMLHttp request.
    xmlHttpRequest.send(Accountxml);
    // Capture the XMLHttp response in XML format.
    var resultXml = xmlHttpRequest.responseXML;

    if (resultXml.selectSingleNode("//q1:address1_city") != null) {         Xrm.Page.getAttribute("address1_city").setValue(resultXml.selectSingleNode("//q1:address1_city").nodeTypedValue);
    }
    else {
        Xrm.Page.getAttribute("address1_city").setValue(null);
    }


    if (resultXml.selectSingleNode("//q1:address1_stateorprovince") != null) {         Xrm.Page.getAttribute("address1_stateorprovince").setValue(resultXml.selectSingleNode("//q1:address1_stateorprovince").nodeTypedValue);
    }
    else {
        Xrm.Page.getAttribute("address1_stateorprovince").setValue(null);
    }

}

Soap XML Retrieve using javascript in CRM 2011

In this article , I am going to explain how to use Soap XML Retrieve web service
http://schemas.microsoft.com/crm/2007/WebServices/Retrieve

In this javascript code i am fetching Account entity address into using  Contact parentcustomerid attribute and filling in Contact address fields

Soap XML retrieve

if (Xrm.Page.getAttribute("parentcustomerid").getValue() != null) {
    //acount guid no
    var parentcustomerID = Xrm.Page.data.entity.attributes.get("parentcustomerid").getValue()[0].id;
    var xml = "<?xml version='1.0' encoding='utf-8'?>" +
    "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'" +
    " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'" +
    " xmlns:xsd='http://www.w3.org/2001/XMLSchema'>" +
    GenerateAuthenticationHeader() +
    "<soap:Body>" +
    "<Retrieve xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>" +
    "<entityName>account</entityName>" +
    "<id>" + parentcustomerID + "</id>" +
    "<columnSet xmlns:q1='http://schemas.microsoft.com/crm/2006/Query' xsi:type='q1:ColumnSet'>" +
        "<q1:Attributes>" +
            "<q1:Attribute>address1_addresstypecode</q1:Attribute>" +
            "<q1:Attribute>address1_name</q1:Attribute>" +
            "<q1:Attribute>address1_line1</q1:Attribute>" +
            "<q1:Attribute>address1_line2</q1:Attribute>" +
            "<q1:Attribute>address1_city</q1:Attribute>" +
            "<q1:Attribute>address1_stateorprovince</q1:Attribute>" +
            "<q1:Attribute>address1_postalcode</q1:Attribute>" +
            "<q1:Attribute>address1_country</q1:Attribute>" +
            "<q1:Attribute>address1_telephone1</q1:Attribute>" +
        "</q1:Attributes>" +
    "</columnSet>" +
    "</Retrieve>" +
    "</soap:Body>" +
    "</soap:Envelope>";
    var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
    xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
    xmlHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Retrieve");
    xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
    xmlHttpRequest.send(xml);
    var resultXml = xmlHttpRequest.responseXML;

    if (resultXml.selectSingleNode("//q1:address1_addresstypecode") != null) { Xrm.Page.getAttribute("address1_addresstypecode").setValue(resultXml.selectSingleNode("//q1:address1_addresstypecode").nodeTypedValue);
    }
    else {
        Xrm.Page.getAttribute("address1_addresstypecode").setValue(null);
    }

    if (resultXml.selectSingleNode("//q1:address1_name") != null) {
Xrm.Page.getAttribute("address1_name").setValue(resultXml.selectSingleNode("//q1:address1_name").nodeTypedValue);
    }
    else {
        Xrm.Page.getAttribute("address1_name").setValue(null);
    }

    if (resultXml.selectSingleNode("//q1:address1_line1") != null) {
Xrm.Page.getAttribute("address1_line1").setValue(resultXml.selectSingleNode("//q1:address1_line1").nodeTypedValue);
    }
    else {
        Xrm.Page.getAttribute("address1_line1").setValue(null);
    }

    if (resultXml.selectSingleNode("//q1:address1_line2") != null) {
Xrm.Page.getAttribute("address1_line2").setValue(resultXml.selectSingleNode("//q1:address1_line2").nodeTypedValue);
    }
    else {
        Xrm.Page.getAttribute("address1_line2").setValue(null);
    }

    if (resultXml.selectSingleNode("//q1:address1_city") != null) {
Xrm.Page.getAttribute("address1_city").setValue(resultXml.selectSingleNode("//q1:address1_city").nodeTypedValue);
    }
    else {
        Xrm.Page.getAttribute("address1_city").setValue(null);
    }

    if (resultXml.selectSingleNode("//q1:address1_stateorprovince") != null) {
Xrm.Page.getAttribute("address1_stateorprovince").setValue(resultXml.selectSingleNode("//q1:address1_stateorprovince").nodeTypedValue);
    }
    else {
        Xrm.Page.getAttribute("address1_stateorprovince").setValue(null);
    }

    if (resultXml.selectSingleNode("//q1:address1_postalcode") != null) {
Xrm.Page.getAttribute("address1_postalcode").setValue(resultXml.selectSingleNode("//q1:address1_postalcode").nodeTypedValue);
    }
    else {
        Xrm.Page.getAttribute("address1_postalcode").setValue(null);
    }

    if (resultXml.selectSingleNode("//q1:address1_country") != null) {
Xrm.Page.getAttribute("address1_country").setValue(resultXml.selectSingleNode("//q1:address1_country").nodeTypedValue);
    }
    else {
        Xrm.Page.getAttribute("address1_country").setValue(null);
    }
}

Open popup window using javascript in CRM 2011

In this article , I am going to explain how to open popup window

CRM function to open a Popup window
var url = "http://crm2011:5555/test/main.aspx?etn=account&pagetype=entityrecord";
var name = "popup";
var width = 800;
var height = 600;
var feature = "status=1";
openStdWin(url, name, width, height, feature);

Set focus on control using javascript in CRM 2011

In this article , I am going to explain how to set focus on control

Set focus
Xrm.Page.getControl("attributename").setFocus(true);

Expand / Collapse tab using javascript in CRM 2011

In this article , I am going to explain how to expand and collapse tabs

Expand tab
Xrm.Page.ui.tabs.get("tabname").setDisplayState('expanded');

Collapse tab
Xrm.Page.ui.tabs.get("tabname").setDisplayState('collapsed');

Thursday, 9 August 2012

Hide and Show section using javascript in CRM 2011

In this article , I am going to explain how to hide section

Hiding Section
Xrm.Page.ui.tabs.get(tabIndex).sections.get(sectionIndex).setVisible(false);
or
Xrm.Page.ui.tabs.get(tabIndex).sections.get("sectionName").setVisible(false);

Showing Section
Xrm.Page.ui.tabs.get(tabIndex).sections.get(sectionIndex).setVisible(true);
or
Xrm.Page.ui.tabs.get(tabIndex).sections.get("sectionName").setVisible(true);

Hide and Show tab using javascript in CRM 2011

In this article , I am going to explain how to hide and show tab

Hiding tab
Xrm.Page.ui.tabs.get(tabindex).setVisible(false);
or
Xrm.Page.ui.tabs.get("tabname").setVisible(false);

Showing tab
Xrm.Page.ui.tabs.get(tabindex).setVisible(true);
or
Xrm.Page.ui.tabs.get("tabname").setVisible(true);

Get data in fields that have changed on form using javascript in CRM 2011

In this article , I am going to explain how to get only changed data

Get changed data 
Xrm.Page.data.entity.getDataXml()



Get current user roles using javascript in CRM 2011

In this article , I am going to explain how to get current user roles

Current user roles
var UserRoles = Xrm.Page.context.getUserRoles();



Retrieve form all controls using javascript in CRM 2011

In this article , I am going to explain how to retrieve form all controls

Retrieve all controls
Xrm.Page.ui.controls.forEach(function (control, index) {
    var attribute = control.getAttribute();
    if (attribute != null) {
        var attributeName = attribute.getName();
    }
});

Refresh ribbon using javascript in CRM 2011

In this article , I am going to explain how to refresh current entity ribbon

Refresh ribbon
Xrm.Page.ui.refreshRibbon()



Attach event to attribute using javascript in CRM 2011

In this article , I am going to explain how to attach event to attribute

Attach event to attribute

crmForm.all.new_isdue.attachEvent("onclick", Onisdueclick);
function  Onisdueclick () {
    alert('Hi');
}


Get Current user id using javascript in CRM 2011

In this article , I am going to explain how to get current user id

Get Current user id
var userID = Xrm.Page.context.getUserId();


Hide a attribute on form using javascript in CRM 2011

In this article , I am going to explain how to hide a attribute on Form

Hide a attribute
Xrm.Page.ui.controls.get("attributename").setVisible(false);



Set focus on control using javascript in CRM 2011

In this article , I am going to explain how to set focus on control

Set focus on control
Xrm.Page.ui.controls.get("attributename").setFocus();