Thursday, December 27, 2012

Reusable JScript Functions


if (typeof (Xrm) == "undefined") Xrm = {};
Xrm.Common = {
    retrieveRecords: function (odataQuery) {
        if (!odataQuery) {
            alert("odataQuery is required.");
            return;
        }

        //The XRM OData end-point
        var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
        var serverUrl = Xrm.Page.context.getServerUrl();
        var records;

        //Asynchronous AJAX function to Retrieve a CRM record using OData
        $.ajax(
{
    type: "GET",
    async: false,
    contentType: "application/json; charset=utf-8",
    datatype: "json",
    url: serverUrl + ODATA_ENDPOINT + "/" + odataQuery,
    beforeSend: function (XMLHttpRequest) {
        //Specifying this header ensures that the results will be returned as JSON.            
        XMLHttpRequest.setRequestHeader("Accept", "application/json");
    },
    success: function (data, textStatus, XmlHttpRequest) {
        records = WEG.Xrm.retrieveRecordsCompleted(data.d, textStatus, XmlHttpRequest);
    },
    error: function (XmlHttpRequest, textStatus, errorThrown) {
        WEG.Xrm.errorHandler(XmlHttpRequest, textStatus, errorThrown);
    }
});
        return records;
    },

    /* Call back method*/
    retrieveRecordsCompleted: function (data, textStatus, XmlHttpRequest) {
        return data.results;
    },

    errorHandler: function (xmlHttpRequest, textStatus, errorThrown) {
        alert("Error : " + textStatus + ": " + xmlHttpRequest.statusText);
    },

    setLookupValue: function (fieldName, id, name, entityType) {
        if (fieldName != null) {
            var lookupValue = new Array();
            lookupValue[0] = new Object();
            lookupValue[0].id = id;
            lookupValue[0].name = name;
            lookupValue[0].entityType = entityType;
            if (Xrm.Page.getAttribute(fieldName) != null)
                Xrm.Page.getAttribute(fieldName).setValue(lookupValue);
        }
    },
    setAttributeValue: function (fieldName, fieldValue) {
        if (fieldName != null) {
            if (Xrm.Page.getAttribute(fieldName) != null) {
                Xrm.Page.getAttribute(fieldName).setValue(fieldValue);
            }
        }
    },

    dateReviver: function (value) {
        var a;
        if (typeof value === 'string') {
            a = /Date\(([-+]?\d+)\)/.exec(value);
            if (a) {
                return new Date(parseInt(value.replace("/Date(", "").replace(")/", ""), 10));
            }
        }
        return value;

    }
}

No comments:

Post a Comment