Skip to main content

Notifications

Microsoft Dynamics CRM (Archived)

How many things will be reusable out of these javascripts.

Posted on by

Hello All Guys,

I need to know about the re usability of the below java script code.

Also if it is reusable then any sample out of it.

var opusUtilities = {
    CRM_ORG_PATH: Xrm.Page.context.getClientUrl() + "/XRMServices/2011/OrganizationData.svc",
    FORM_TYPE_CREATE: 1,

    retrieveProductDescription: function (productId) {
        var description = "";
        var oDataSelect = "/ProductSet?$select=Name&$filter=ProductId eq guid\'" + productId + "\'";
        var product = this.querySingleEntity(oDataSelect);

        if (product != null) {
            description = product.Name;
        }

        return description;
    },

    queryMultipleEntities: function (oDataSelect) {
        var resultEntities = null;
        // Perform a synchronous oData retrieve
        $.ajax({
            type: "GET",
            async: false,
            contentType: "application/json; charset=utf-8",
            datatype: "json",
            url: opusUtilities.CRM_ORG_PATH + oDataSelect,
            beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
            success: function (data, textStatus, XmlHttpRequest) {
                // The query was successful, so check if there are any records and return them
                if ((data != undefined) && (data.d != undefined) && (data.d.results.length > 0)) {
                    resultEntities = data.d.results;
                }
            },
            error: function (XmlHttpRequest, textStatus, errorThrown) { alert('OData Select Failed: ' + oDataSelect); }
        });

        return resultEntities;
    },

    retrieveProductsDefaultUOM: function (productId) {
        var defaultUOM = null;

        var oDataSelect = "/ProductSet?$select=DefaultUoMId&$filter=ProductId eq guid\'" + productId + "\'";
        var product = this.querySingleEntity(oDataSelect);

        if (product != null) {
            defaultUOM = product.DefaultUoMId;
        }

        return defaultUOM;
    },



    UserHasRole: function (roleName) {
        var bHasRole = false;

        var oDataSelect = "/RoleSet?$filter=Name eq \'" + roleName + "\'";
        var roles = this.queryMultipleEntities(oDataSelect);

        if (roles.length > 0) {
            var currentUserRoles = Xrm.Page.context.getUserRoles();
            for (var x = 0; x < roles.length; x++) {
                if (bHasRole == true) {
                    break;
                }
                var rData = roles[x];
                var retrievedRole = rData.RoleId;
                for (var i = 0; i < currentUserRoles.length; i++) {
                    var userRole = currentUserRoles[i];

                    if (this.GuidsAreEqual(userRole, retrievedRole)) {
                        bHasRole = true;
                        break;
                    }
                }
            }
        }

        return bHasRole;
    },

    queryToCheckConditions: function (oDataSelect) {
        var resultBool = false;

        // Perform a synchronous oData retrieve
        $.ajax({
            type: "GET",
            async: false,
            contentType: "application/json; charset=utf-8",
            datatype: "json",
            url: opusUtilities.CRM_ORG_PATH + oDataSelect,
            beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
            success: function (data, textStatus, XmlHttpRequest) {
                // The query was successful, so check if a record was returned
                if ((data != undefined) && (data.d != undefined) && (data.d.results[0] != null) && (data.d.results.length == 1)) {
                    resultBool = true;
                }
            },
            error: function (XmlHttpRequest, textStatus, errorThrown) { alert('OData Select Failed: ' + oDataSelect); }
        });

        return resultBool;
    },

    GuidsAreEqual: function (guid1, guid2) {
        var isEqual = false;
        if (guid1 == null || guid2 == null) {
            isEqual = false;
        }
        else {
            isEqual = guid1.replace(/[{}]/g, "").toLowerCase() == guid2.replace(/[{}]/g, "").toLowerCase();
        }

        return isEqual;
    },

    setBillToShipToCustomerNames: function () {
        if ((Xrm.Page.ui.getFormType() == opusUtilities.FORM_TYPE_CREATE) || (Xrm.Page.getAttribute("new_billtocustomer").getValue() == null && Xrm.Page.getAttribute("new_shiptocustomer").getValue() == null)) {
            if (Xrm.Page.getAttribute("customerid").getValue() != null) {
                var customerLookupItem = Xrm.Page.getAttribute("customerid").getValue();

                if (customerLookupItem != null) {
                    var customerName = customerLookupItem[0].name;

                    Xrm.Page.getAttribute("new_billtocustomer").setValue(customerName);
                    Xrm.Page.getAttribute("new_shiptocustomer").setValue(customerName);
                }
            }
        }
    },

    setOptionSetByOptionText: function (optionsetAttribute, optionText) {
        var options = Xrm.Page.getAttribute(optionsetAttribute).getOptions();
        for (i = 0; i < options.length; i++) {
            if (options[i].text == optionText) {
                Xrm.Page.getAttribute(optionsetAttribute).setValue(options[i].value);
            }
        }
    },

    setRequirementLevel: function (fieldName, reqLevel) {
        Xrm.Page.getAttribute(fieldName).setRequiredLevel(reqLevel);
    },

    setDisabled: function (fieldName, accessible) {
        Xrm.Page.ui.controls.get(fieldName).setDisabled(accessible);
    },

    setVisibility: function (fieldName, visible) {
        Xrm.Page.ui.controls.get(fieldName).setVisible(visible);
    },

    setFieldValue: function (fieldToSet, setToValue) {
        if (Xrm.Page.getAttribute(fieldToSet) != null) {
            Xrm.Page.getAttribute(fieldToSet).setValue(setToValue);
            Xrm.Page.getAttribute(fieldToSet).setSubmitMode("always");
        }
    },

    getFieldValue: function (fieldToGet) {
        return Xrm.Page.getAttribute(fieldToGet).getValue();
    },

    getLookupId: function (c) {
        //c = control name
        var lookupObject = Xrm.Page.getAttribute(c);

        if (lookupObject != null) {
            var lookUpObjectValue = lookupObject.getValue();

            if ((lookUpObjectValue != null)) {
                //var lookuptextvalue = lookUpObjectValue[0].name;
                var lookupid = lookUpObjectValue[0].id;
            }
        }
        return lookupid;
    },

    getLookupName: function (c) {
        //c = control name
        var lookupObject = Xrm.Page.getAttribute(c);
        var lookuptextvalue = "";

        if (lookupObject != null) {
            var lookUpObjectValue = lookupObject.getValue();

            if ((lookUpObjectValue != null)) {
                lookuptextvalue = lookUpObjectValue[0].name;
            }
        }
        return lookuptextvalue;
    },

    saveForm: function () {
        return Xrm.Page.data.entity.save();
    },

    getEntityId: function () {
        return Xrm.Page.data.entity.getId();
    },

    querySingleEntity: function (oDataSelect) {
        var resultEntity = null;

        // Perform a synchronous oData retrieve
        $.ajax({
            type: "GET",
            async: false,
            contentType: "application/json; charset=utf-8",
            datatype: "json",
            url: opusUtilities.CRM_ORG_PATH + oDataSelect,
            beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
            success: function (data, textStatus, XmlHttpRequest) {
                // The query was successful, so check if there is a record and return it
                if ((data != undefined) && (data.d != undefined) && (data.d.results[0] != null)) {
                    resultEntity = data.d.results[0];
                }
            },
            error: function (XmlHttpRequest, textStatus, errorThrown) { alert('OData Select Failed: ' + oDataSelect); }
        });

        return resultEntity;
    },

    getJsonObjectForField: function (responseFieldName) {
        var jsonText = opusUtilities.getFieldValue(responseFieldName);

        if (jsonText !== null && jsonText !== undefined) {
            try {
                var responseObj = JSON.parse(jsonText);
                if (responseObj !== null) {
                    return responseObj;
                }
            }
            catch (exception) {
                alert("json parsing error.");
                return null;
            }
        }

        // always return null if jsonText is null or undefined
        return null;
    },


    ChangeAllAttributeGradientMask: function () {
        var elements = document.getElementsByClassName("ms-crm-Inline-GradientMask");
        for (var i = 0; i < elements.length; i++) {
            if (elements[i] != null) {
                elements[i].style.display = "none";
            }
        }
    },

    ChangeBackgroundColor: function (Control) {
        if (Control != null) {
            Control.style.backgroundColor = "#F3F3F4";
        }
    },
}



*This post is locked for comments

  • Suggested answer
    Rajkumar Rajaraman Profile Picture
    Rajkumar Rajaraman 18,108 on at
    RE: How many things will be reusable out of these javascripts.

    Refer Aileen's post in the following thread:

    community.dynamics.com/.../149322

    Hope this helps

  • EmployeeOcta Profile Picture
    EmployeeOcta on at
    RE: How many things will be reusable out of these javascripts.

    Hello Guys,

    can you guys provide me some sample example w.r.t. that.

  • Suggested answer
    Rajkumar Rajaraman Profile Picture
    Rajkumar Rajaraman 18,108 on at
    RE: How many things will be reusable out of these javascripts.

    You can create one webresource (Library file) and append the code after that call based on events (like onchange,onload and onsave)

  • Suggested answer
    Gopalan Bhuvanesh Profile Picture
    Gopalan Bhuvanesh 11,397 on at
    RE: How many things will be reusable out of these javascripts.

    All functions can be used (as utility library).

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Tips for Writing Effective Suggested Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,253 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,188 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans