Common ready to Use JavaScript function for MSCRM 13+


How to refresh the subgrid on Form using javascript in MSCRM

function addEventToGridRefresh(gridName, functiontoCall) {
    // retrieve the subgrid
    var grid = Xrm.Page.getControl(gridName);
    // if the subgrid still not available we try again after 1 second
    if (grid == null) {
        setTimeout(function () { addEventToGridRefresh(gridName, functiontoCall); }, 1000);
        return;
    }
}

Hiding Option set values By using Javascript

function hideoption(){
var myPicklist = Xrm.Page.getControl("new_test");
myPicklist.removeOption(3);
}

How to refresh Iframe in MSCRM using javascript

function refreshIFRAME(iframeName) {

    var IFrame = Xrm.Page.ui.controls.get(iframeName);
    alert(IFrame);

    if (IFrame != null) {
        IFrame.refresh();
    }
}

DOB Validation in MSCRM using javascript

function validateDOB(fileName) {

    var dateOfBirth = Xrm.Page.getAttribute(fileName).getValue();
    var d1 = new Date();
    var date1 = new Date(d1.getFullYear() - 18, d1.getMonth(), d1.getDate());
    if (date1 < dateOfBirth) {
        Xrm.Page.ui.clearFormNotification("dateofbirthNotification");
        Xrm.Page.ui.setFormNotification('Age Cannot be less than 18 years.', 'ERROR', "dateofbirthNotification");
    }
    else {
        Xrm.Page.ui.clearFormNotification("dateofbirthNotification");
    }
}

To get GetCRMDateFormatValue

function getCRMDateFormatValue(dtDate) {
    var odataDate = dtDate;
    odataDate = odataDate.replace('/Date(', '');
    odataDate = odataDate.replace(')/', '');
    var crmDateValue = new Date(parseInt(odataDate, 10));
    crmDateValue.setDate(crmDateValue.getDate());
    return crmDateValue;
}
function getRequestObject() {
    if (window.XMLHttpRequest) { return new window.XMLHttpRequest; }
    else {
        try { return new ActiveXObject("MSXML2.XMLHTTP.3.0"); }
        catch (ex) { return null; }
    }
}
function makeRequest(query) {
    var serverUrl = Xrm.Page.context.getClientUrl();
    var oDataEndpointUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc/";
    oDataEndpointUrl += query; var service = getRequestObject();
    if (service != null) {
        service.open("GET", oDataEndpointUrl, false);
        service.setRequestHeader("X-Requested-With", "XMLHttpRequest");
        service.setRequestHeader("Accept", "application/json, text/javascript, */*");
        service.send(null); var retrieved = JSON.parse(service.responseText).d;

        var results = new Array();
        if (retrieved.results != null) {
            for (var i = 0; i  passedDate2) {
                return false;
            }
 else {
                return true;
            }
        }
        else {
            return true;
        }
    }
 catch (e) { }
}

DOB Validation

function validateDOBOnSave(context, eventTypeCode, fieldName) {
    var dateOfBirth = null;
    try {
        if (Xrm.Page.getAttribute("mo_dateofbirth") == null) {
            Xrm.Utilities.alertDialog("Field is not placed in the form.", function () { })
            return;
        }
        dateOfBirth = Xrm.Page.getAttribute(mo_dateofbirth).getValue();
        var d1 = new Date();
        var date1 = new Date(d1.getFullYear() - 18, d1.getMonth(), d1.getDate());
        if (dateOfBirth != null && date1 < dateOfBirth) {
            Xrm.Page.ui.clearFormNotification("birthday");
            Xrm.Page.ui.setFormNotification('Age cannot be less than 18 years.', 'ERROR', "birthday");
            if (eventTypeCode == 1) {
                context.getEventArgs().preventDefault();
                return false;
            }
        }
        else {
            Xrm.Page.ui.clearFormNotification("birthday");
        }
    } catch (e) {
        onError(e, "validateDOBOnSave");
    }
}

How to disable all the fields in MSCRM using Javascript

function disableFields() {
    if (Xrm.Page.ui.getFormType() != 1) {
        var controls = Xrm.Page.ui.controls.get();
        for (var i in controls) {
            var control = controls[i];
            if (!control.getDisabled()) {
                control.setDisabled(true);
            }
        }
    }
}

//Disable fields inside a section of a tab
//tabNumber is name of teh tab,
//sectionNumber is the name of the section,
//disablestatus is true or false, depends if you want to disable pass true else false.

    function sectionSetDisabled(tabNumber, sectionNumber, disablestatus) {
        debugger;
        var section = Xrm.Page.ui.tabs.get(tabNumber).sections.get(sectionNumber);
        var controls = section.controls.get();
        var controlsLenght = controls.length;

        for (var i = 0; i < controlsLenght; i++) {
            controls[i].setDisabled(disablestatus)
        }
    }

How to Get/Check User Roles in MSCRM using javascript.

function checkUserRole(roleName) {
    var currentUserRoles = Xrm.Page.context.getUserRoles();
    for (var i = 0; i < currentUserRoles.length; i++) {
        var userRoleId = currentUserRoles[i];
        var userRoleName = getRoleName(userRoleId);
        if (userRoleName == roleName) {
            return true;
        }
    }
}

 

Get User Role

function getRoleName(userRoleId) {
    var selectQuery = "RoleSet?$top=1&amp;$filter=RoleId eq guid'" + userRoleId + "'&amp;$select=Name";
    var url = Xrm.Page.context.getClientUrl() + "/XRMServices/2011/OrganizationData.svc/";
    var odataSelect = url + selectQuery;
    var roleName = null;
    $.ajax({
        type: "GET",
        async: false,
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: odataSelect,
        beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
        success: function (data, textStatus, XmlHttpRequest) {
            var result = data.d;
            if (!!result) {
                roleName = result.results[0].Name;
            }
        },
        error: function (XmlHttpRequest, textStatus, errorThrown) {
        }
    });
    return roleName;
}

Show Alert Dialog

function onError(e, functionName) {
    try {
        Xrm.Utilities.alertDialog(functionName + " " + (e.message || e.description), function () { });
    } catch (e) {
        alert(functionName + ": " + (e.message || e.description));
    }
}

Age Validation

function checkAge() {
    var birthdate = Xrm.Page.getAttribute("birthdate").getValue();
    var d1 = new Date();
    var date1 = new Date(d1.getFullYear() - 18, d1.getMonth(), d1.getDate());
    if (date1 & amp; lt; birthdate) {
        Xrm.Page.ui.clearFormNotification("birthdate");
        Xrm.Page.ui.setFormNotification('Age Cannot be less than 18 years.', 'ERROR', "birthdate");
    }
    else {
        Xrm.Page.ui.clearFormNotification("birthdate");
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s