locked
Odata Service to retrieve multiple RRS feed

  • Question

  • Hi All,

    I am having a requirement like onchange of one field in code entity need to hit another entity called gravity in which get the values from there and compare those . if those values lies in between the values in gravity then I need to get the value from gravity field and set it to the code entity.

    I am new to use this service please help me ...

    Please post me the helpful code

    Monday, June 16, 2014 7:02 AM

Answers

  • Hi,

    Use this function onChange on your field:

    function getRange()
    {
    	var gravityid = Xrm.Page.data.entity.getId();
    	var OgsValue = Xrm.Page.getAttribute("ms_offensegravityscore").getValue();
    
    	var option = "$select=ms_gravitylevelId,ms_name,ms_Range,ms_ScoresFrom,ms_ScoresTo&$filter=(msjps_ScoresFrom ge " + OgsValue + " and ms_ScoresTo le " + OgsValue + ")";
    	
    	SDK.REST.retrieveMultipleRecords("Account", option, retrieveRecordsCallBack, function(error) { alert(error.message); }, function(){});
    }
    
    function retrieveRecordsCallBack(recordsObject)
    {
    	if (recordsObject!= null && recordsObject.length > 0)
    	{
    		for (var i = 0; i < recordsObject.length; i++)
    		{
    			//access your data like recordsObject[i].ms_gravitylevelId, recordsObject[i].ms_name, recordsObject[i].ms_Range, etc.
    			//var _name = recordsObject[i].ms_name; --> like this
    		}
    	}
    	else
    	{
    		alert("Error");
    	}
    }

    Create a second web resource named sdk.rest.js  and put this as content:

    // =====================================================================
    //  This file is part of the Microsoft Dynamics CRM SDK code samples.
    //
    //  Copyright (C) Microsoft Corporation.  All rights reserved.
    //
    //  This source code is intended only as a supplement to Microsoft
    //  Development Tools and/or on-line documentation.  See these other
    //  materials for detailed information regarding Microsoft code samples.
    //
    //  THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
    //  KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
    //  IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
    //  PARTICULAR PURPOSE.
    // =====================================================================
    // <snippetSDKRESTJS>
    if (typeof (SDK) == "undefined")
    { SDK = { __namespace: true }; }
    SDK.REST = {
     _context: function () {
      ///<summary>
      /// Private function to the context object.
      ///</summary>
      ///<returns>Context</returns>
      if (typeof GetGlobalContext != "undefined")
      { return GetGlobalContext(); }
      else {
       if (typeof Xrm != "undefined") {
        return Xrm.Page.context;
       }
       else
       { throw new Error("Context is not available."); }
      }
     },
     _getClientUrl: function () {
      ///<summary>
      /// Private function to return the server URL from the context
      ///</summary>
      ///<returns>String</returns>
      var clientUrl = this._context().getClientUrl()
    
      return clientUrl;
     },
     _ODataPath: function () {
      ///<summary>
      /// Private function to return the path to the REST endpoint.
      ///</summary>
      ///<returns>String</returns>
      return this._getClientUrl() + "/XRMServices/2011/OrganizationData.svc/";
     },
     _errorHandler: function (req) {
      ///<summary>
      /// Private function return an Error object to the errorCallback
      ///</summary>
      ///<param name="req" type="XMLHttpRequest">
      /// The XMLHttpRequest response that returned an error.
      ///</param>
      ///<returns>Error</returns>
      //Error descriptions come from http://support.microsoft.com/kb/193625
      if (req.status == 12029)
      { return new Error("The attempt to connect to the server failed."); }
      if (req.status == 12007)
      { return new Error("The server name could not be resolved."); }
      var errorText;
      try
            { errorText = JSON.parse(req.responseText).error.message.value; }
      catch (e)
            { errorText = req.responseText }
    
      return new Error("Error : " +
            req.status + ": " +
            req.statusText + ": " + errorText);
     },
     _dateReviver: function (key, value) {
      ///<summary>
      /// Private function to convert matching string values to Date objects.
      ///</summary>
      ///<param name="key" type="String">
      /// The key used to identify the object property
      ///</param>
      ///<param name="value" type="String">
      /// The string value representing a date
      ///</param>
      var a;
      if (typeof value === 'string') {
       a = /Date\(([-+]?\d+)\)/.exec(value);
       if (a) {
        return new Date(parseInt(value.replace("/Date(", "").replace(")/", ""), 10));
       }
      }
      return value;
     },
     _parameterCheck: function (parameter, message) {
      ///<summary>
      /// Private function used to check whether required parameters are null or undefined
      ///</summary>
      ///<param name="parameter" type="Object">
      /// The parameter to check;
      ///</param>
      ///<param name="message" type="String">
      /// The error message text to include when the error is thrown.
      ///</param>
      if ((typeof parameter === "undefined") || parameter === null) {
       throw new Error(message);
      }
     },
     _stringParameterCheck: function (parameter, message) {
      ///<summary>
      /// Private function used to check whether required parameters are null or undefined
      ///</summary>
      ///<param name="parameter" type="String">
      /// The string parameter to check;
      ///</param>
      ///<param name="message" type="String">
      /// The error message text to include when the error is thrown.
      ///</param>
      if (typeof parameter != "string") {
       throw new Error(message);
      }
     },
     _callbackParameterCheck: function (callbackParameter, message) {
      ///<summary>
      /// Private function used to check whether required callback parameters are functions
      ///</summary>
      ///<param name="callbackParameter" type="Function">
      /// The callback parameter to check;
      ///</param>
      ///<param name="message" type="String">
      /// The error message text to include when the error is thrown.
      ///</param>
      if (typeof callbackParameter != "function") {
       throw new Error(message);
      }
     },
     createRecord: function (object, type, successCallback, errorCallback) {
      ///<summary>
      /// Sends an asynchronous request to create a new record.
      ///</summary>
      ///<param name="object" type="Object">
      /// A JavaScript object with properties corresponding to the Schema name of
      /// entity attributes that are valid for create operations.
      ///</param>
      ///<param name="type" type="String">
      /// The Schema Name of the Entity type record to create.
      /// For an Account record, use "Account"
      ///</param>
      ///<param name="successCallback" type="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.
      /// </param>
      ///<param name="errorCallback" type="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.
      /// </param>
      this._parameterCheck(object, "SDK.REST.createRecord requires the object parameter.");
      this._stringParameterCheck(type, "SDK.REST.createRecord requires the type parameter is a string.");
      this._callbackParameterCheck(successCallback, "SDK.REST.createRecord requires the successCallback is a function.");
      this._callbackParameterCheck(errorCallback, "SDK.REST.createRecord requires the errorCallback is a function.");
      var req = new XMLHttpRequest();
      req.open("POST", encodeURI(this._ODataPath() + type + "Set"), true);
      req.setRequestHeader("Accept", "application/json");
      req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
      req.onreadystatechange = function () {
       if (this.readyState == 4 /* complete */) {
        req.onreadystatechange = null;
        if (this.status == 201) {
         successCallback(JSON.parse(this.responseText, SDK.REST._dateReviver).d);
        }
        else {
         errorCallback(SDK.REST._errorHandler(this));
        }
       }
      };
      req.send(JSON.stringify(object));
     },
     retrieveRecord: function (id, type, select, expand, successCallback, errorCallback) {
      ///<summary>
      /// Sends an asynchronous request to retrieve a record.
      ///</summary>
      ///<param name="id" type="String">
      /// A String representing the GUID value for the record to retrieve.
      ///</param>
      ///<param name="type" type="String">
      /// The Schema Name of the Entity type record to retrieve.
      /// For an Account record, use "Account"
      ///</param>
      ///<param name="select" type="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
      ///</param>
      ///<param name="expand" type="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 of up to 6 entity relationship names
      /// If null no expanded related records will be returned.
      ///</param>
      ///<param name="successCallback" type="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.
      /// </param>
      ///<param name="errorCallback" type="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.
      /// </param>
      this._stringParameterCheck(id, "SDK.REST.retrieveRecord requires the id parameter is a string.");
      this._stringParameterCheck(type, "SDK.REST.retrieveRecord requires the type parameter is a string.");
      if (select != null)
       this._stringParameterCheck(select, "SDK.REST.retrieveRecord requires the select parameter is a string.");
      if (expand != null)
       this._stringParameterCheck(expand, "SDK.REST.retrieveRecord requires the expand parameter is a string.");
      this._callbackParameterCheck(successCallback, "SDK.REST.retrieveRecord requires the successCallback parameter is a function.");
      this._callbackParameterCheck(errorCallback, "SDK.REST.retrieveRecord requires the errorCallback parameter is a function.");
    
      var systemQueryOptions = "";
    
      if (select != null || expand != null) {
       systemQueryOptions = "?";
       if (select != null) {
        var selectString = "$select=" + select;
        if (expand != null) {
         selectString = selectString + "," + expand;
        }
        systemQueryOptions = systemQueryOptions + selectString;
       }
       if (expand != null) {
        systemQueryOptions = systemQueryOptions + "&$expand=" + expand;
       }
      }
    
    
      var req = new XMLHttpRequest();
      req.open("GET", encodeURI(this._ODataPath() + type + "Set(guid'" + id + "')" + systemQueryOptions), true);
      req.setRequestHeader("Accept", "application/json");
      req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
      req.onreadystatechange = function () {
       if (this.readyState == 4 /* complete */) {
        req.onreadystatechange = null;
        if (this.status == 200) {
         successCallback(JSON.parse(this.responseText, SDK.REST._dateReviver).d);
        }
        else {
         errorCallback(SDK.REST._errorHandler(this));
        }
       }
      };
      req.send();
     },
     updateRecord: function (id, object, type, successCallback, errorCallback) {
      ///<summary>
      /// Sends an asynchronous request to update a record.
      ///</summary>
      ///<param name="id" type="String">
      /// A String representing the GUID value for the record to retrieve.
      ///</param>
      ///<param name="object" type="Object">
      /// A JavaScript object with properties corresponding to the Schema Names for
      /// entity attributes that are valid for update operations.
      ///</param>
      ///<param name="type" type="String">
      /// The Schema Name of the Entity type record to retrieve.
      /// For an Account record, use "Account"
      ///</param>
      ///<param name="successCallback" type="Function">
      /// The function that will be passed through and be called by a successful response. 
      /// Nothing will be returned to this function.
      /// </param>
      ///<param name="errorCallback" type="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.
      /// </param>
      this._stringParameterCheck(id, "SDK.REST.updateRecord requires the id parameter.");
      this._parameterCheck(object, "SDK.REST.updateRecord requires the object parameter.");
      this._stringParameterCheck(type, "SDK.REST.updateRecord requires the type parameter.");
      this._callbackParameterCheck(successCallback, "SDK.REST.updateRecord requires the successCallback is a function.");
      this._callbackParameterCheck(errorCallback, "SDK.REST.updateRecord requires the errorCallback is a function.");
      var req = new XMLHttpRequest();
    
      req.open("POST", encodeURI(this._ODataPath() + type + "Set(guid'" + id + "')"), true);
      req.setRequestHeader("Accept", "application/json");
      req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
      req.setRequestHeader("X-HTTP-Method", "MERGE");
      req.onreadystatechange = function () {
       if (this.readyState == 4 /* complete */) {
        req.onreadystatechange = null;
        if (this.status == 204 || this.status == 1223) {
         successCallback();
        }
        else {
         errorCallback(SDK.REST._errorHandler(this));
        }
       }
      };
      req.send(JSON.stringify(object));
     },
     deleteRecord: function (id, type, successCallback, errorCallback) {
      ///<summary>
      /// Sends an asynchronous request to delete a record.
      ///</summary>
      ///<param name="id" type="String">
      /// A String representing the GUID value for the record to delete.
      ///</param>
      ///<param name="type" type="String">
      /// The Schema Name of the Entity type record to delete.
      /// For an Account record, use "Account"
      ///</param>
      ///<param name="successCallback" type="Function">
      /// The function that will be passed through and be called by a successful response. 
      /// Nothing will be returned to this function.
      /// </param>
      ///<param name="errorCallback" type="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.
      /// </param>
      this._stringParameterCheck(id, "SDK.REST.deleteRecord requires the id parameter.");
      this._stringParameterCheck(type, "SDK.REST.deleteRecord requires the type parameter.");
      this._callbackParameterCheck(successCallback, "SDK.REST.deleteRecord requires the successCallback is a function.");
      this._callbackParameterCheck(errorCallback, "SDK.REST.deleteRecord requires the errorCallback is a function.");
      var req = new XMLHttpRequest();
      req.open("POST", encodeURI(this._ODataPath() + type + "Set(guid'" + id + "')"), true);
      req.setRequestHeader("Accept", "application/json");
      req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
      req.setRequestHeader("X-HTTP-Method", "DELETE");
      req.onreadystatechange = function () {
    
       if (this.readyState == 4 /* complete */) {
        req.onreadystatechange = null;
        if (this.status == 204 || this.status == 1223) {
         successCallback();
        }
        else {
         errorCallback(SDK.REST._errorHandler(this));
        }
       }
      };
      req.send();
    
     },
     retrieveMultipleRecords: function (type, options, successCallback, errorCallback, OnComplete) {
      ///<summary>
      /// Sends an asynchronous request to retrieve records.
      ///</summary>
      ///<param name="type" type="String">
      /// The Schema Name of the Entity type record to retrieve.
      /// For an Account record, use "Account"
      ///</param>
      ///<param name="options" type="String">
      /// A String representing the OData System Query Options to control the data returned
      ///</param>
      ///<param name="successCallback" type="Function">
      /// The function that will be passed through and be called for each page of records returned.
      /// Each page is 50 records. If you expect that more than one page of records will be returned,
      /// this function should loop through the results and push the records into an array outside of the function.
      /// Use the OnComplete event handler to know when all the records have been processed.
      /// </param>
      ///<param name="errorCallback" type="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.
      /// </param>
      ///<param name="OnComplete" type="Function">
      /// The function that will be called when all the requested records have been returned.
      /// No parameters are passed to this function.
      /// </param>
      this._stringParameterCheck(type, "SDK.REST.retrieveMultipleRecords requires the type parameter is a string.");
      if (options != null)
       this._stringParameterCheck(options, "SDK.REST.retrieveMultipleRecords requires the options parameter is a string.");
      this._callbackParameterCheck(successCallback, "SDK.REST.retrieveMultipleRecords requires the successCallback parameter is a function.");
      this._callbackParameterCheck(errorCallback, "SDK.REST.retrieveMultipleRecords requires the errorCallback parameter is a function.");
      this._callbackParameterCheck(OnComplete, "SDK.REST.retrieveMultipleRecords requires the OnComplete parameter is a function.");
    
      var optionsString;
      if (options != null) {
       if (options.charAt(0) != "?") {
        optionsString = "?" + options;
       }
       else
       { optionsString = options; }
      }
      var req = new XMLHttpRequest();
      req.open("GET", this._ODataPath() + type + "Set" + optionsString, false);
      req.setRequestHeader("Accept", "application/json");
      req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
      req.onreadystatechange = function () {
       if (this.readyState == 4 /* complete */) {
        req.onreadystatechange = null;
        if (this.status == 200) {
         var returned = JSON.parse(this.responseText, SDK.REST._dateReviver).d;
         successCallback(returned.results);
         if (returned.__next != null) {
          var queryOptions = returned.__next.substring((SDK.REST._ODataPath() + type + "Set").length);
          SDK.REST.retrieveMultipleRecords(type, queryOptions, successCallback, errorCallback, OnComplete);
         }
         else
         { OnComplete(); }
        }
        else {
         errorCallback(SDK.REST._errorHandler(this));
        }
       }
      };
      req.send();
     },
     associateRecords: function (parentId, parentType, relationshipName, childId, childType, successCallback, errorCallback) {
      this._stringParameterCheck(parentId, "SDK.REST.associateRecords requires the parentId parameter is a string.");
      ///<param name="parentId" type="String">
      /// The Id of the record to be the parent record in the relationship
      /// </param>
      ///<param name="parentType" type="String">
      /// The Schema Name of the Entity type for the parent record.
      /// For an Account record, use "Account"
      /// </param>
      ///<param name="relationshipName" type="String">
      /// The Schema Name of the Entity Relationship to use to associate the records.
      /// To associate account records as a Parent account, use "Referencedaccount_parent_account"
      /// </param>
      ///<param name="childId" type="String">
      /// The Id of the record to be the child record in the relationship
      /// </param>
      ///<param name="childType" type="String">
      /// The Schema Name of the Entity type for the child record.
      /// For an Account record, use "Account"
      /// </param>
      ///<param name="successCallback" type="Function">
      /// The function that will be passed through and be called by a successful response. 
      /// Nothing will be returned to this function.
      /// </param>
      ///<param name="errorCallback" type="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.
      /// </param>
      this._stringParameterCheck(parentType, "SDK.REST.associateRecords requires the parentType parameter is a string.");
      this._stringParameterCheck(relationshipName, "SDK.REST.associateRecords requires the relationshipName parameter is a string.");
      this._stringParameterCheck(childId, "SDK.REST.associateRecords requires the childId parameter is a string.");
      this._stringParameterCheck(childType, "SDK.REST.associateRecords requires the childType parameter is a string.");
      this._callbackParameterCheck(successCallback, "SDK.REST.associateRecords requires the successCallback parameter is a function.");
      this._callbackParameterCheck(errorCallback, "SDK.REST.associateRecords requires the errorCallback parameter is a function.");
    
      var req = new XMLHttpRequest();
      req.open("POST", encodeURI(this._ODataPath() + parentType + "Set(guid'" + parentId + "')/$links/" + relationshipName), true);
      req.setRequestHeader("Accept", "application/json");
      req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
      req.onreadystatechange = function () {
       if (this.readyState == 4 /* complete */) {
        req.onreadystatechange = null;
        if (this.status == 204 || this.status == 1223) {
         successCallback();
        }
        else {
         errorCallback(SDK.REST._errorHandler(this));
        }
       }
      };
      var childEntityReference = {}
      childEntityReference.uri = this._ODataPath() + "/" + childType + "Set(guid'" + childId + "')";
      req.send(JSON.stringify(childEntityReference));
     },
     disassociateRecords: function (parentId, parentType, relationshipName, childId, successCallback, errorCallback) {
      this._stringParameterCheck(parentId, "SDK.REST.disassociateRecords requires the parentId parameter is a string.");
      ///<param name="parentId" type="String">
      /// The Id of the record to be the parent record in the relationship
      /// </param>
      ///<param name="parentType" type="String">
      /// The Schema Name of the Entity type for the parent record.
      /// For an Account record, use "Account"
      /// </param>
      ///<param name="relationshipName" type="String">
      /// The Schema Name of the Entity Relationship to use to disassociate the records.
      /// To disassociate account records as a Parent account, use "Referencedaccount_parent_account"
      /// </param>
      ///<param name="childId" type="String">
      /// The Id of the record to be disassociated as the child record in the relationship
      /// </param>
      ///<param name="successCallback" type="Function">
      /// The function that will be passed through and be called by a successful response. 
      /// Nothing will be returned to this function.
      /// </param>
      ///<param name="errorCallback" type="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.
      /// </param>
      this._stringParameterCheck(parentType, "SDK.REST.disassociateRecords requires the parentType parameter is a string.");
      this._stringParameterCheck(relationshipName, "SDK.REST.disassociateRecords requires the relationshipName parameter is a string.");
      this._stringParameterCheck(childId, "SDK.REST.disassociateRecords requires the childId parameter is a string.");
      this._callbackParameterCheck(successCallback, "SDK.REST.disassociateRecords requires the successCallback parameter is a function.");
      this._callbackParameterCheck(errorCallback, "SDK.REST.disassociateRecords requires the errorCallback parameter is a function.");
    
      var req = new XMLHttpRequest();
      req.open("POST", encodeURI(this._ODataPath() + parentType + "Set(guid'" + parentId + "')/$links/" + relationshipName + "(guid'" + childId + "')"), true);
      req.setRequestHeader("Accept", "application/json");
      req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
      req.setRequestHeader("X-HTTP-Method", "DELETE");
      req.onreadystatechange = function () {
       if (this.readyState == 4 /* complete */) {
        req.onreadystatechange = null;
        if (this.status == 204 || this.status == 1223) {
         successCallback();
        }
        else {
         errorCallback(SDK.REST._errorHandler(this));
        }
       }
      };
      req.send();
     },
     __namespace: true
    };
    // </snippetSDKRESTJS>

    Make a third web resource named as json2.js with this content:

    if (!this.JSON) { this.JSON = {}; } (function () { function f(n) { return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function (key) { return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (key) { return this.valueOf(); }; } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\\': '\\\\' }, rep; function quote(string) { escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { var i, k, v, length, mind = gap, partial, value = holder[key]; if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } if (typeof rep === 'function') { value = rep.call(holder, key, value); } switch (typeof value) { case 'string': return quote(value); case 'number': return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': return String(value); case 'object': if (!value) { return 'null'; } gap += indent; partial = []; if (Object.prototype.toString.apply(value) === '[object Array]') { length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { k = rep[i]; if (typeof k === 'string') { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } if (typeof JSON.stringify !== 'function') { JSON.stringify = function (value, replacer, space) { var i; gap = ''; indent = ''; if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } } else if (typeof space === 'string') { indent = space; } rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } return str('', { '': value }); }; } if (typeof JSON.parse !== 'function') { JSON.parse = function (text, reviver) { var j; function walk(holder, key) { var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } if (/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { j = eval('(' + text + ')'); return typeof reviver === 'function' ? walk({ '': j }, '') : j; } throw new SyntaxError('JSON.parse'); }; } } ());

    Just add the sdk.rest.js and json2.js in the form library of the entity form.


    Admin QuikView Solution for CRM 2013


    Wednesday, June 18, 2014 10:37 AM

All replies

  • Hi,

    Download the CRM 2013 SDK and go to the following path : "\SDK\SampleCode\JS\RESTEndpoint\JavaScriptRESTRetrieveMultiple\JavaScriptRESTRetrieveMultiple". There's a sample to assist you.

    You need to upload the SDK.REST.js and json2.js files as web resource, use a similar code as follows to construct your OData query and you will get an idea of how it works:

    function fieldNameOnChange()
    {
    	//fetch your entity field data using Xrm.Page.getAttribute("field_name").getValue();
    
    	//construct your oData query. I suggest downloading the OData query designer from http://crm2011odatatool.codeplex.com/
    	//sample of Odata : var option = "$select=AccountName&$filter=AccountId eq guid'" + accountId + "'";
    	
    	//call SDK retrieve multiple to fetch data 
    	SDK.REST.retrieveMultipleRecords("Account", option, retrieveAccountsCallBack, function(error) { alert(error.message); }, function(){});
    }
    
    function retrieveAccountsCallBack(accountDetails)
    {
    	if ((accountDetails!= null))
    	{
    		var accountName = accountDetails[0].AccountName;
    	}
    	else
    	{
    		alert("Error");
    	}
    }

    I recommend downloading the OData Query Designer to make your queries: http://crm2011odatatool.codeplex.com/


    Admin QuikView Solution for CRM 2013

    Monday, June 16, 2014 7:10 AM
  • Here you have an example of a simple oData function to query CRM.

    http://tiagolvsantos.wordpress.com/2014/01/21/odata-query-example/

    This is a query example:

    Query += "AccountSet?$select=AccountId&$filter=AccountId eq guid'" + customerid +"'";

    Good Luck :)

    Monday, June 16, 2014 10:09 AM
  • Hi,

    I am unable to understand your code. It should be something like this:

    function init()
    {
    	var option = "$select=ms_gravitylevel&$filter=field_Name eq " + field_Value + "'";
    	SDK.REST.retrieveMultipleRecords("ms_gravitylevel", option, retrieveRecordsCallBack, function(error) { alert(error.message); }, function(){});
    }
    
    function retrieveRecordsCallBack(recordsObject)
    {
    	if (recordsObject!= null)
    	{
    		var accountNumber = recordsObject[0].ms_scoresfrom;
    		var AccountName = recordsObject[0].ms_scoresto;
    
    	}
    	else
    	{
    		alert("Error");
    	}
    }


    Admin QuikView Solution for CRM 2013

    Wednesday, June 18, 2014 6:34 AM
  • function

    GetRange(OgsValue) {

       

       

    vargravityid = Xrm.Page.data.entity.getId();

       

    varOgsValue = Xrm.Page.getAttribute("ms_offensegravityscore").getValue();

        alert(OgsValue);

       

    varoDataPath = Xrm.Page.context.getServerUrl() + "/xrmservices/2011/organizationdata.svc";

       

    varretrieveReq = newXMLHttpRequest();

       

    varOdata = oDataPath + "/ms_gravitylevelSet?$select=ms_gravitylevelId,ms_name,ms_Range,ms_ScoresFrom,ms_ScoresTo&$filter=msjps_ScoresFrom ge +"OgsValue"+ and ms_ScoresTo le +"OgsValue"+";

        retrieveReq.open(

    "GET", Odata, false);

        retrieveReq.setRequestHeader(

    "Accept", "application/json");

        retrieveReq.setRequestHeader(

    "Content-Type", "application/json; charset=utf-8");

        retrieveReq.onreadystatechange =

    function() { RetrieveReqCallBack(this); };

        retrieveReq.send();

    }

    function

    RetrieveReqCallBack(retrieveReq) {

        }

    I wrote the above function now I need to get the value range from the returned result will you please give the code the for "RetrieveReqCallBack" function

    Please help me I am struggling this from 3 days and also please let me know which files I need to add to the library.

    Thanks in advance

        }

    }

    Wednesday, June 18, 2014 10:13 AM
  • Hi,

    Use this function onChange on your field:

    function getRange()
    {
    	var gravityid = Xrm.Page.data.entity.getId();
    	var OgsValue = Xrm.Page.getAttribute("ms_offensegravityscore").getValue();
    
    	var option = "$select=ms_gravitylevelId,ms_name,ms_Range,ms_ScoresFrom,ms_ScoresTo&$filter=(msjps_ScoresFrom ge " + OgsValue + " and ms_ScoresTo le " + OgsValue + ")";
    	
    	SDK.REST.retrieveMultipleRecords("Account", option, retrieveRecordsCallBack, function(error) { alert(error.message); }, function(){});
    }
    
    function retrieveRecordsCallBack(recordsObject)
    {
    	if (recordsObject!= null && recordsObject.length > 0)
    	{
    		for (var i = 0; i < recordsObject.length; i++)
    		{
    			//access your data like recordsObject[i].ms_gravitylevelId, recordsObject[i].ms_name, recordsObject[i].ms_Range, etc.
    			//var _name = recordsObject[i].ms_name; --> like this
    		}
    	}
    	else
    	{
    		alert("Error");
    	}
    }

    Create a second web resource named sdk.rest.js  and put this as content:

    // =====================================================================
    //  This file is part of the Microsoft Dynamics CRM SDK code samples.
    //
    //  Copyright (C) Microsoft Corporation.  All rights reserved.
    //
    //  This source code is intended only as a supplement to Microsoft
    //  Development Tools and/or on-line documentation.  See these other
    //  materials for detailed information regarding Microsoft code samples.
    //
    //  THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
    //  KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
    //  IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
    //  PARTICULAR PURPOSE.
    // =====================================================================
    // <snippetSDKRESTJS>
    if (typeof (SDK) == "undefined")
    { SDK = { __namespace: true }; }
    SDK.REST = {
     _context: function () {
      ///<summary>
      /// Private function to the context object.
      ///</summary>
      ///<returns>Context</returns>
      if (typeof GetGlobalContext != "undefined")
      { return GetGlobalContext(); }
      else {
       if (typeof Xrm != "undefined") {
        return Xrm.Page.context;
       }
       else
       { throw new Error("Context is not available."); }
      }
     },
     _getClientUrl: function () {
      ///<summary>
      /// Private function to return the server URL from the context
      ///</summary>
      ///<returns>String</returns>
      var clientUrl = this._context().getClientUrl()
    
      return clientUrl;
     },
     _ODataPath: function () {
      ///<summary>
      /// Private function to return the path to the REST endpoint.
      ///</summary>
      ///<returns>String</returns>
      return this._getClientUrl() + "/XRMServices/2011/OrganizationData.svc/";
     },
     _errorHandler: function (req) {
      ///<summary>
      /// Private function return an Error object to the errorCallback
      ///</summary>
      ///<param name="req" type="XMLHttpRequest">
      /// The XMLHttpRequest response that returned an error.
      ///</param>
      ///<returns>Error</returns>
      //Error descriptions come from http://support.microsoft.com/kb/193625
      if (req.status == 12029)
      { return new Error("The attempt to connect to the server failed."); }
      if (req.status == 12007)
      { return new Error("The server name could not be resolved."); }
      var errorText;
      try
            { errorText = JSON.parse(req.responseText).error.message.value; }
      catch (e)
            { errorText = req.responseText }
    
      return new Error("Error : " +
            req.status + ": " +
            req.statusText + ": " + errorText);
     },
     _dateReviver: function (key, value) {
      ///<summary>
      /// Private function to convert matching string values to Date objects.
      ///</summary>
      ///<param name="key" type="String">
      /// The key used to identify the object property
      ///</param>
      ///<param name="value" type="String">
      /// The string value representing a date
      ///</param>
      var a;
      if (typeof value === 'string') {
       a = /Date\(([-+]?\d+)\)/.exec(value);
       if (a) {
        return new Date(parseInt(value.replace("/Date(", "").replace(")/", ""), 10));
       }
      }
      return value;
     },
     _parameterCheck: function (parameter, message) {
      ///<summary>
      /// Private function used to check whether required parameters are null or undefined
      ///</summary>
      ///<param name="parameter" type="Object">
      /// The parameter to check;
      ///</param>
      ///<param name="message" type="String">
      /// The error message text to include when the error is thrown.
      ///</param>
      if ((typeof parameter === "undefined") || parameter === null) {
       throw new Error(message);
      }
     },
     _stringParameterCheck: function (parameter, message) {
      ///<summary>
      /// Private function used to check whether required parameters are null or undefined
      ///</summary>
      ///<param name="parameter" type="String">
      /// The string parameter to check;
      ///</param>
      ///<param name="message" type="String">
      /// The error message text to include when the error is thrown.
      ///</param>
      if (typeof parameter != "string") {
       throw new Error(message);
      }
     },
     _callbackParameterCheck: function (callbackParameter, message) {
      ///<summary>
      /// Private function used to check whether required callback parameters are functions
      ///</summary>
      ///<param name="callbackParameter" type="Function">
      /// The callback parameter to check;
      ///</param>
      ///<param name="message" type="String">
      /// The error message text to include when the error is thrown.
      ///</param>
      if (typeof callbackParameter != "function") {
       throw new Error(message);
      }
     },
     createRecord: function (object, type, successCallback, errorCallback) {
      ///<summary>
      /// Sends an asynchronous request to create a new record.
      ///</summary>
      ///<param name="object" type="Object">
      /// A JavaScript object with properties corresponding to the Schema name of
      /// entity attributes that are valid for create operations.
      ///</param>
      ///<param name="type" type="String">
      /// The Schema Name of the Entity type record to create.
      /// For an Account record, use "Account"
      ///</param>
      ///<param name="successCallback" type="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.
      /// </param>
      ///<param name="errorCallback" type="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.
      /// </param>
      this._parameterCheck(object, "SDK.REST.createRecord requires the object parameter.");
      this._stringParameterCheck(type, "SDK.REST.createRecord requires the type parameter is a string.");
      this._callbackParameterCheck(successCallback, "SDK.REST.createRecord requires the successCallback is a function.");
      this._callbackParameterCheck(errorCallback, "SDK.REST.createRecord requires the errorCallback is a function.");
      var req = new XMLHttpRequest();
      req.open("POST", encodeURI(this._ODataPath() + type + "Set"), true);
      req.setRequestHeader("Accept", "application/json");
      req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
      req.onreadystatechange = function () {
       if (this.readyState == 4 /* complete */) {
        req.onreadystatechange = null;
        if (this.status == 201) {
         successCallback(JSON.parse(this.responseText, SDK.REST._dateReviver).d);
        }
        else {
         errorCallback(SDK.REST._errorHandler(this));
        }
       }
      };
      req.send(JSON.stringify(object));
     },
     retrieveRecord: function (id, type, select, expand, successCallback, errorCallback) {
      ///<summary>
      /// Sends an asynchronous request to retrieve a record.
      ///</summary>
      ///<param name="id" type="String">
      /// A String representing the GUID value for the record to retrieve.
      ///</param>
      ///<param name="type" type="String">
      /// The Schema Name of the Entity type record to retrieve.
      /// For an Account record, use "Account"
      ///</param>
      ///<param name="select" type="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
      ///</param>
      ///<param name="expand" type="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 of up to 6 entity relationship names
      /// If null no expanded related records will be returned.
      ///</param>
      ///<param name="successCallback" type="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.
      /// </param>
      ///<param name="errorCallback" type="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.
      /// </param>
      this._stringParameterCheck(id, "SDK.REST.retrieveRecord requires the id parameter is a string.");
      this._stringParameterCheck(type, "SDK.REST.retrieveRecord requires the type parameter is a string.");
      if (select != null)
       this._stringParameterCheck(select, "SDK.REST.retrieveRecord requires the select parameter is a string.");
      if (expand != null)
       this._stringParameterCheck(expand, "SDK.REST.retrieveRecord requires the expand parameter is a string.");
      this._callbackParameterCheck(successCallback, "SDK.REST.retrieveRecord requires the successCallback parameter is a function.");
      this._callbackParameterCheck(errorCallback, "SDK.REST.retrieveRecord requires the errorCallback parameter is a function.");
    
      var systemQueryOptions = "";
    
      if (select != null || expand != null) {
       systemQueryOptions = "?";
       if (select != null) {
        var selectString = "$select=" + select;
        if (expand != null) {
         selectString = selectString + "," + expand;
        }
        systemQueryOptions = systemQueryOptions + selectString;
       }
       if (expand != null) {
        systemQueryOptions = systemQueryOptions + "&$expand=" + expand;
       }
      }
    
    
      var req = new XMLHttpRequest();
      req.open("GET", encodeURI(this._ODataPath() + type + "Set(guid'" + id + "')" + systemQueryOptions), true);
      req.setRequestHeader("Accept", "application/json");
      req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
      req.onreadystatechange = function () {
       if (this.readyState == 4 /* complete */) {
        req.onreadystatechange = null;
        if (this.status == 200) {
         successCallback(JSON.parse(this.responseText, SDK.REST._dateReviver).d);
        }
        else {
         errorCallback(SDK.REST._errorHandler(this));
        }
       }
      };
      req.send();
     },
     updateRecord: function (id, object, type, successCallback, errorCallback) {
      ///<summary>
      /// Sends an asynchronous request to update a record.
      ///</summary>
      ///<param name="id" type="String">
      /// A String representing the GUID value for the record to retrieve.
      ///</param>
      ///<param name="object" type="Object">
      /// A JavaScript object with properties corresponding to the Schema Names for
      /// entity attributes that are valid for update operations.
      ///</param>
      ///<param name="type" type="String">
      /// The Schema Name of the Entity type record to retrieve.
      /// For an Account record, use "Account"
      ///</param>
      ///<param name="successCallback" type="Function">
      /// The function that will be passed through and be called by a successful response. 
      /// Nothing will be returned to this function.
      /// </param>
      ///<param name="errorCallback" type="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.
      /// </param>
      this._stringParameterCheck(id, "SDK.REST.updateRecord requires the id parameter.");
      this._parameterCheck(object, "SDK.REST.updateRecord requires the object parameter.");
      this._stringParameterCheck(type, "SDK.REST.updateRecord requires the type parameter.");
      this._callbackParameterCheck(successCallback, "SDK.REST.updateRecord requires the successCallback is a function.");
      this._callbackParameterCheck(errorCallback, "SDK.REST.updateRecord requires the errorCallback is a function.");
      var req = new XMLHttpRequest();
    
      req.open("POST", encodeURI(this._ODataPath() + type + "Set(guid'" + id + "')"), true);
      req.setRequestHeader("Accept", "application/json");
      req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
      req.setRequestHeader("X-HTTP-Method", "MERGE");
      req.onreadystatechange = function () {
       if (this.readyState == 4 /* complete */) {
        req.onreadystatechange = null;
        if (this.status == 204 || this.status == 1223) {
         successCallback();
        }
        else {
         errorCallback(SDK.REST._errorHandler(this));
        }
       }
      };
      req.send(JSON.stringify(object));
     },
     deleteRecord: function (id, type, successCallback, errorCallback) {
      ///<summary>
      /// Sends an asynchronous request to delete a record.
      ///</summary>
      ///<param name="id" type="String">
      /// A String representing the GUID value for the record to delete.
      ///</param>
      ///<param name="type" type="String">
      /// The Schema Name of the Entity type record to delete.
      /// For an Account record, use "Account"
      ///</param>
      ///<param name="successCallback" type="Function">
      /// The function that will be passed through and be called by a successful response. 
      /// Nothing will be returned to this function.
      /// </param>
      ///<param name="errorCallback" type="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.
      /// </param>
      this._stringParameterCheck(id, "SDK.REST.deleteRecord requires the id parameter.");
      this._stringParameterCheck(type, "SDK.REST.deleteRecord requires the type parameter.");
      this._callbackParameterCheck(successCallback, "SDK.REST.deleteRecord requires the successCallback is a function.");
      this._callbackParameterCheck(errorCallback, "SDK.REST.deleteRecord requires the errorCallback is a function.");
      var req = new XMLHttpRequest();
      req.open("POST", encodeURI(this._ODataPath() + type + "Set(guid'" + id + "')"), true);
      req.setRequestHeader("Accept", "application/json");
      req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
      req.setRequestHeader("X-HTTP-Method", "DELETE");
      req.onreadystatechange = function () {
    
       if (this.readyState == 4 /* complete */) {
        req.onreadystatechange = null;
        if (this.status == 204 || this.status == 1223) {
         successCallback();
        }
        else {
         errorCallback(SDK.REST._errorHandler(this));
        }
       }
      };
      req.send();
    
     },
     retrieveMultipleRecords: function (type, options, successCallback, errorCallback, OnComplete) {
      ///<summary>
      /// Sends an asynchronous request to retrieve records.
      ///</summary>
      ///<param name="type" type="String">
      /// The Schema Name of the Entity type record to retrieve.
      /// For an Account record, use "Account"
      ///</param>
      ///<param name="options" type="String">
      /// A String representing the OData System Query Options to control the data returned
      ///</param>
      ///<param name="successCallback" type="Function">
      /// The function that will be passed through and be called for each page of records returned.
      /// Each page is 50 records. If you expect that more than one page of records will be returned,
      /// this function should loop through the results and push the records into an array outside of the function.
      /// Use the OnComplete event handler to know when all the records have been processed.
      /// </param>
      ///<param name="errorCallback" type="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.
      /// </param>
      ///<param name="OnComplete" type="Function">
      /// The function that will be called when all the requested records have been returned.
      /// No parameters are passed to this function.
      /// </param>
      this._stringParameterCheck(type, "SDK.REST.retrieveMultipleRecords requires the type parameter is a string.");
      if (options != null)
       this._stringParameterCheck(options, "SDK.REST.retrieveMultipleRecords requires the options parameter is a string.");
      this._callbackParameterCheck(successCallback, "SDK.REST.retrieveMultipleRecords requires the successCallback parameter is a function.");
      this._callbackParameterCheck(errorCallback, "SDK.REST.retrieveMultipleRecords requires the errorCallback parameter is a function.");
      this._callbackParameterCheck(OnComplete, "SDK.REST.retrieveMultipleRecords requires the OnComplete parameter is a function.");
    
      var optionsString;
      if (options != null) {
       if (options.charAt(0) != "?") {
        optionsString = "?" + options;
       }
       else
       { optionsString = options; }
      }
      var req = new XMLHttpRequest();
      req.open("GET", this._ODataPath() + type + "Set" + optionsString, false);
      req.setRequestHeader("Accept", "application/json");
      req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
      req.onreadystatechange = function () {
       if (this.readyState == 4 /* complete */) {
        req.onreadystatechange = null;
        if (this.status == 200) {
         var returned = JSON.parse(this.responseText, SDK.REST._dateReviver).d;
         successCallback(returned.results);
         if (returned.__next != null) {
          var queryOptions = returned.__next.substring((SDK.REST._ODataPath() + type + "Set").length);
          SDK.REST.retrieveMultipleRecords(type, queryOptions, successCallback, errorCallback, OnComplete);
         }
         else
         { OnComplete(); }
        }
        else {
         errorCallback(SDK.REST._errorHandler(this));
        }
       }
      };
      req.send();
     },
     associateRecords: function (parentId, parentType, relationshipName, childId, childType, successCallback, errorCallback) {
      this._stringParameterCheck(parentId, "SDK.REST.associateRecords requires the parentId parameter is a string.");
      ///<param name="parentId" type="String">
      /// The Id of the record to be the parent record in the relationship
      /// </param>
      ///<param name="parentType" type="String">
      /// The Schema Name of the Entity type for the parent record.
      /// For an Account record, use "Account"
      /// </param>
      ///<param name="relationshipName" type="String">
      /// The Schema Name of the Entity Relationship to use to associate the records.
      /// To associate account records as a Parent account, use "Referencedaccount_parent_account"
      /// </param>
      ///<param name="childId" type="String">
      /// The Id of the record to be the child record in the relationship
      /// </param>
      ///<param name="childType" type="String">
      /// The Schema Name of the Entity type for the child record.
      /// For an Account record, use "Account"
      /// </param>
      ///<param name="successCallback" type="Function">
      /// The function that will be passed through and be called by a successful response. 
      /// Nothing will be returned to this function.
      /// </param>
      ///<param name="errorCallback" type="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.
      /// </param>
      this._stringParameterCheck(parentType, "SDK.REST.associateRecords requires the parentType parameter is a string.");
      this._stringParameterCheck(relationshipName, "SDK.REST.associateRecords requires the relationshipName parameter is a string.");
      this._stringParameterCheck(childId, "SDK.REST.associateRecords requires the childId parameter is a string.");
      this._stringParameterCheck(childType, "SDK.REST.associateRecords requires the childType parameter is a string.");
      this._callbackParameterCheck(successCallback, "SDK.REST.associateRecords requires the successCallback parameter is a function.");
      this._callbackParameterCheck(errorCallback, "SDK.REST.associateRecords requires the errorCallback parameter is a function.");
    
      var req = new XMLHttpRequest();
      req.open("POST", encodeURI(this._ODataPath() + parentType + "Set(guid'" + parentId + "')/$links/" + relationshipName), true);
      req.setRequestHeader("Accept", "application/json");
      req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
      req.onreadystatechange = function () {
       if (this.readyState == 4 /* complete */) {
        req.onreadystatechange = null;
        if (this.status == 204 || this.status == 1223) {
         successCallback();
        }
        else {
         errorCallback(SDK.REST._errorHandler(this));
        }
       }
      };
      var childEntityReference = {}
      childEntityReference.uri = this._ODataPath() + "/" + childType + "Set(guid'" + childId + "')";
      req.send(JSON.stringify(childEntityReference));
     },
     disassociateRecords: function (parentId, parentType, relationshipName, childId, successCallback, errorCallback) {
      this._stringParameterCheck(parentId, "SDK.REST.disassociateRecords requires the parentId parameter is a string.");
      ///<param name="parentId" type="String">
      /// The Id of the record to be the parent record in the relationship
      /// </param>
      ///<param name="parentType" type="String">
      /// The Schema Name of the Entity type for the parent record.
      /// For an Account record, use "Account"
      /// </param>
      ///<param name="relationshipName" type="String">
      /// The Schema Name of the Entity Relationship to use to disassociate the records.
      /// To disassociate account records as a Parent account, use "Referencedaccount_parent_account"
      /// </param>
      ///<param name="childId" type="String">
      /// The Id of the record to be disassociated as the child record in the relationship
      /// </param>
      ///<param name="successCallback" type="Function">
      /// The function that will be passed through and be called by a successful response. 
      /// Nothing will be returned to this function.
      /// </param>
      ///<param name="errorCallback" type="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.
      /// </param>
      this._stringParameterCheck(parentType, "SDK.REST.disassociateRecords requires the parentType parameter is a string.");
      this._stringParameterCheck(relationshipName, "SDK.REST.disassociateRecords requires the relationshipName parameter is a string.");
      this._stringParameterCheck(childId, "SDK.REST.disassociateRecords requires the childId parameter is a string.");
      this._callbackParameterCheck(successCallback, "SDK.REST.disassociateRecords requires the successCallback parameter is a function.");
      this._callbackParameterCheck(errorCallback, "SDK.REST.disassociateRecords requires the errorCallback parameter is a function.");
    
      var req = new XMLHttpRequest();
      req.open("POST", encodeURI(this._ODataPath() + parentType + "Set(guid'" + parentId + "')/$links/" + relationshipName + "(guid'" + childId + "')"), true);
      req.setRequestHeader("Accept", "application/json");
      req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
      req.setRequestHeader("X-HTTP-Method", "DELETE");
      req.onreadystatechange = function () {
       if (this.readyState == 4 /* complete */) {
        req.onreadystatechange = null;
        if (this.status == 204 || this.status == 1223) {
         successCallback();
        }
        else {
         errorCallback(SDK.REST._errorHandler(this));
        }
       }
      };
      req.send();
     },
     __namespace: true
    };
    // </snippetSDKRESTJS>

    Make a third web resource named as json2.js with this content:

    if (!this.JSON) { this.JSON = {}; } (function () { function f(n) { return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function (key) { return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (key) { return this.valueOf(); }; } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\\': '\\\\' }, rep; function quote(string) { escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { var i, k, v, length, mind = gap, partial, value = holder[key]; if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } if (typeof rep === 'function') { value = rep.call(holder, key, value); } switch (typeof value) { case 'string': return quote(value); case 'number': return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': return String(value); case 'object': if (!value) { return 'null'; } gap += indent; partial = []; if (Object.prototype.toString.apply(value) === '[object Array]') { length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { k = rep[i]; if (typeof k === 'string') { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } if (typeof JSON.stringify !== 'function') { JSON.stringify = function (value, replacer, space) { var i; gap = ''; indent = ''; if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } } else if (typeof space === 'string') { indent = space; } rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } return str('', { '': value }); }; } if (typeof JSON.parse !== 'function') { JSON.parse = function (text, reviver) { var j; function walk(holder, key) { var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } if (/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { j = eval('(' + text + ')'); return typeof reviver === 'function' ? walk({ '': j }, '') : j; } throw new SyntaxError('JSON.parse'); }; } } ());

    Just add the sdk.rest.js and json2.js in the form library of the entity form.


    Admin QuikView Solution for CRM 2013


    Wednesday, June 18, 2014 10:37 AM