‏إظهار الرسائل ذات التسميات JavaScript. إظهار كافة الرسائل
‏إظهار الرسائل ذات التسميات JavaScript. إظهار كافة الرسائل

الأربعاء، 6 سبتمبر 2017

Dynamics 365 / CRM 2016 : Using Web API Operations - Retrieve Single or Multiple Records

In MS CRM 2016, Web API introduced to perform operations on MS CRM using JavaScript. 

      function retrieveSingleRecord (entityDefinitions, recordId) {
        /// <summary>
        /// Retrieving single record using Web API by record ID.
        /// </summary>
        /// <param name="entityDefinitions" type="string">
        /// EntitySetName (ex:for Account entity, the entity set name is accounts)
        /// </param>
        /// <param name="recordId" type="string">
        /// A string represents a guid for record Id.
        /// </param>
        /// <returns type="Object" />

        recordId = recordId.replace(/[\{\}]+/g, '');

        var apiUrl = Xrm.Page.context.getClientUrl() + "/api/data/v8.1/" + entityDefinitions + "(" + recordId + ")";

        var req = GetRequestObject();

        if (req != null) {
            req.open("GET", apiUrl, false);
            req.setRequestHeader("OData-MaxVersion", "4.0");
            req.setRequestHeader("OData-Version", "4.0");
            req.setRequestHeader("Accept", "application/json");
            req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
            req.setRequestHeader("Prefer", "odata.include-annotations=OData.Community.Display.V1.FormattedValue");
            req.send(null);

            var requestResults = JSON.parse(req.response)

            return requestResults;
        }
        return false;
    }
//**************************************************************************
    function retrieveSingleRecord_WithCallBack (entityDefinitions, recordId, successCallBackFun) {
        /// <summary>
        /// Retrieving single record using Web API by record ID with callback function.
        /// </summary>
        /// <param name="entityDefinitions" type="string">
        /// EntitySetName (ex:for Account entity, the entity set name is accounts)
        /// </param>
        /// <param name="recordId" type="string">
        /// A string represents a guid for record Id.
        /// </param>
        /// <param name="successCallBackFun" type="function">
        /// callback function.
        /// </param>
        /// <returns type="void" />

        recordId = recordId.replace(/[\{\}]+/g, '');

        var apiUrl = Xrm.Page.context.getClientUrl()+ "/api/data/v8.1/" + entityDefinitions + "(" + recordId + ")";

        //Ex:https://vvvvv.crm4.dynamics.com/api/data/v8.2/accounts(A0A00F3A-1166-E711-80E1-3863BB343B78)

        var req = new XMLHttpRequest();
        req.open("GET", apiUrl, true);
        req.setRequestHeader("OData-MaxVersion", "4.0");
        req.setRequestHeader("OData-Version", "4.0");
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.setRequestHeader("Prefer", "odata.include-annotations=OData.Community.Display.V1.FormattedValue");

        req.onreadystatechange = function () {
            if (this.readyState === 4) {
                req.onreadystatechange = null;
                if (this.status === 200) {
                    var result = JSON.parse(this.response);
                    //alert(result["name"]);
                    successCallBackFun(result);
                }
                else {
                    alert(this.statusText);
                }
            }
        };
        req.send();
    }

//**************************************************************************

    function retrieveMultiple (entityDefinitions, filterUrl) {

        /// <summary>
        /// Retrieving multiple records based on specific filter criteria.
        /// </summary>
        /// <param name="entityDefinitions" type="string">
        /// EntitySetName (ex:for Account entity, the entity set name is accounts)
        /// </param>
        /// <param name="filterUrl" type="string">
        /// a string url to specify filter criteria using $filter(ex:$filter=cusomerid eq cusomeridvalue).
        /// </param>
        /// <returns type="Object" />

        var apiUrl = Xrm.Page.context.getClientUrl() + "/api/data/v8.1/" + entityDefinitions + "?" + filterUrl + "&$count=true";

        var req = GetRequestObject();

        if (req != null) {
            req.open("GET", apiUrl, false);
            req.setRequestHeader("OData-MaxVersion", "4.0");
            req.setRequestHeader("OData-Version", "4.0");
            req.setRequestHeader("Accept", "application/json");
            req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
            req.setRequestHeader("Prefer", "odata.include-annotations=OData.Community.Display.V1.FormattedValue");
            req.send(null);
            var requestResults = JSON.parse(req.response)

            return requestResults;
        }
        return false;
    }

Dynamics 365:How to filter lookup control based on another lookup value using JavaScript

Ex:Display only the contacts that belong to selected account.

//when account lookup value changed
function onAccountChanged() {
    var AccountId = getLookupValue("customerid");
    if (AccountId != null) {

        Xrm.Page.getControl("contactid").removePreSearch(function () {
            addLookupFilter();
        });

        Xrm.Page.getControl("contactid").addPreSearch(function () {
            addLookupFilter();
        });

        Xrm.Page.getAttribute("contactid").setValue(null);
    }

    else {

        Xrm.Page.getControl("contactid").removePreSearch(function () {
            addLookupFilter();
        });

        Xrm.Page.getAttribute("contactid").setValue(null);

    }
}

function addLookupFilter() { 
    var accountId = getLookupValue("customerid"); 

    var fetchXml = "<filter type='and'><condition value='" + accountId + "' attribute='parentcustomerid' uitype='account'  operator='eq' /></filter>";
    Xrm.Page.getControl("alfa_address").addCustomFilter(fetchXml);
}
 //***************************
function getLookupValue(fieldname) {
    var lookupObj = Xrm.Page.getAttribute(fieldname);
    if (lookupObj.getValue() != null)
        return lookupObj.getValue()[0].id;
    else
        return null;
};

الخميس، 7 يناير 2016

CRM 2011: Hiding Ribbon Button on Click/Select SubGrid using JavaScript.

function OnSubGridClicked() {
    var GridCtrl = document.getElementById("gridname");
    if (GridCtrl == null || GridCtrl.readyState != "complete") {
        setTimeout('OnSubGridClicked()', 1000);
        return;
    }
    else {
        GridCtrl.onload = HideRibbon;
        GridCtrl.onclick = HideRibbon;
        GridCtrl.onfocus = HideRibbon;
    }
}

function HideRibbon() {
    if (window.top.document.getElementById("RibbonId") != null) {
        window.top.document.getElementById("RibbonId").style.display = "none";
        setTimeout(" HideRibbon('"RibbonId"');", 200);
    }
}

الثلاثاء، 22 ديسمبر 2015

Google Chrome browser error:xmlhttprequest cannot load is not allowed by access-control-allow-origin

In that case you can change the security policy in your Google Chrome browser to allow Access-Control-Allow-Origin. This is very simple:
  1. Create a Chrome browser shortcut
  2. Right click short cut icon -> Properties -> Shortcut -> Target
Simple paste in "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files --disable-web-security.


الجمعة، 1 مايو 2015

Open Entity Form (New/existing) using JavaScript

//Open a new contact record
Xrm.Utility.openEntityForm("contact");
//Open an existing contact record
Xrm.Utility.openEntityForm("contact","A85C0252-DF8B-E111-997C-00155D8A8410");
//Open a new contact record with a specific form and setting default values
var parameters = {};
parameters["formid"] = "b053a39a-041a-4356-acef-ddf00182762b";
parameters["name"] = "New Contact";
parameters["emailaddress"] = "email@example.com";
//For lookup
parameters["customerid"] = "257b689C8B47-8B9D-E111-883B-1CC1DEEA2718";
parameters["customeridname"] = "Test Cust";

Xrm.Utility.openEntityForm("contact", null, parameters);
//Open a new contact record, move it to the top left corner of the screen, and set the size of the window
var newWindow = Xrm.Utility.openEntityForm("contact");
newWindow.moveTo(0,0);
newWindow.resizeTo(800,600);

///*******************************************************
Opens an HTML web resource:

//**Open an HTML web resource named "new_webResource.htm":
Xrm.Utility.openWebResource("new_webResource.htm");



//**Open an HTML web resource including a single item of data for the data parameter
Xrm.Utility.openWebResource("new_webResource.htm","dataItemValue");



//**Open an HTML web resource passing multiple values through the data parameter
var customParameters = encodeURIComponent("first=First Value&second=Second Value&third=Third Value");
Xrm.Utility.openWebResource("new_webResource.htm",customParameters);

الأحد، 26 أبريل 2015

Open CRM Lookup window in a custom page

function OpenLookup() {
    var serverURL = "http://Server:5555/OrganizationName/_controls/lookup/lookupinfo.aspx?AllowFilterOff=1&DefaultType=2&DefaultViewId=%7b00000000-0000-0000-00AA-000010001004%7d&DisableQuickFind=0&DisableViewPicker=0&LookupStyle=single&ShowNewButton=1&ShowPropButton=1&browse=0&objecttypes=123";


    var lookUp = window.showModalDialog(serverURL, 'entity', "dialogwidth: 750px; dialogheight: 600px; resizable: yes");

    ///For get return values

    //var name = lookUp.items[0].name; var id = lookUp.items[0].id;
    if (lookUp != null) {
        var data = eval('(' + lookUp + ')');
        alert(data.items[0].name + ":" + data.items[0].id);
    }
}

الاثنين، 20 أبريل 2015

Dynamics CRM 2013:Get/Set Business Process stage field value.

Xrm.Page.getControl("header_process_fieldname").getAttribute().setValue(value);  //Set Value

Xrm.Page.getControl("header_process_fieldname").getAttribute().getValue();  //Get Value

 //****** get the Id of business process Satge*******************************
    var StageId = Xrm.Page.getAttribute("stageid").getValue();
    
    if (StageId == "7f5247fe-cfc3-42bc-aa77-b1d836d9b7c0") {
        var Control = Xrm.Page.getControl("header_process_fieldname").getAttribute();
//fire onChange event.
        Control.addOnChange(FunctionName);
    }

الأحد، 26 يناير 2014

CRM 2011: Set the focus to control

function ControlSetFocus(fieldName) {
    var attribute = Xrm.Page.data.entity.attributes.get(fieldName);
    var control = attribute.controls.get(0);
    control.setFocus(true);
}

CRM 2011 Validate required form using javascript


This code checks if form is valid for saving, by going over all required attributes and checking if it contains value.

function IsFormValidForSaving(){
var valid = true; Xrm.Page.data.entity.attributes.forEach(function (attribute, index) { if (attribute.getRequiredLevel() == "required") { if (attribute.getValue() == null) { if (valid) { var control = attribute.controls.get(0); alert(control.getLabel() + " Field is empty"); control.setFocus(); } valid = false; } } }); return valid;
}
http://dynamicslollipops.blogspot.com/2012/07/microsoft-dynamics-crm-2011-validate.html

الخميس، 23 يناير 2014

CRM2011:Syntax error... /userdefined/edit.aspx?etc=

When I was using Visual Ribbon Editor, I added a group and a button to trigger a JavaScript function in a JavaScript Library, I was using CRM 2011 and rollup 12, I found this:
Issue:
If you upgraded to CRM 2011 rollup 12 already and use Visual Ribbon Editor to create button, and the action of  button is calling a JavaScript function in a JavaScript Library, you might get a JavaScript Syntax Error.
Solution:
Add $webresource: in front of you JavaScript library.
For examples:
in if you JavaScript library name is: myJavaScriptLibrary.js, then should specify like like this:
$webresource:myJavaScriptLibrary.js
OR
/WebResources/myJavascriptLibrary

الأحد، 5 يناير 2014

Execute workflow using javascript in CRM 2011

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 = '33dce53c-9107-4148-9712-52f83742e6b3';
        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');
        }
    }
}