Category: Java Script Dynamics CRM

On Form Load Check the User Team and Lock the form the if the owner of the record team doesn’t matches with Logged in user.

Following code will help you in the following:

  • getting the team names in the system
  • getting the team associated with the user.
  • validating the action if the team name doesn’t match

On Load Function that calls the getCurrentUserTeamNames

function Form_OnLoad_ValidateUserTeam() {
    var userTeams = getCurrentUserTeamNames();
    if (userTeams != null && userTeams.length > 0) {
        if (!isValidateFormAccess(userTeams)) {
            DisableFormFields();
        }
    }
}

function isValidateFormAccess(userTeams) {
    debugger;
    var recordOwner = Xrm.Page.getControl("header_ownerid").getAttribute().getValue();
 
    //var myStringArray = ["Hello", "World"];
    var userTeamsLength = userTeams.length;
    for (var i = 0; i < userTeamsLength; i++) {
        if (userTeams[i] == recordOwner[0].name) {
            return true;
        }   //Do something
    }
    return false;
}

GetCurrentUserTeamNames: this function will return the team names of the user

function getCurrentUserTeamNames() {
    debugger;
    //ajax call to get data from CRM
    var serverUrl = location.protocol + "//" + location.host + "/" + Xrm.Page.context.getOrgUniqueName();
    var odataSelect = serverUrl + "/XRMServices/2011/OrganizationData.svc" + "/" + "TeamSet?$select=Name,TeamId";
    var userTeams = [];
    $.ajax
    (
     {
         type: "GET",
         contentType: "application/json; charset=utf-8",
         datatype: "json",
         async: false,
         url: odataSelect,
         beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
         success: function (data, textStatus, XmlHttpRequest) {
             for (var i = 0; i < data.d.results.length; i++) {                  if (Check(data.d.results[i].TeamId)) {                      //alert("You are associated with team: " + data.d.results[i].Name);                        userTeams.push(data.d.results[i].Name);                  }              }              },            error: function (XmlHttpRequest, textStatus, errorThrown) {              if (XmlHttpRequest && XmlHttpRequest.responseText) {                  alert('OData Select Failed: ' + textStatus + errorThrown + odataSelect);              }          }      }     );       return userTeams; }       function Check(teamid) {       var userId = Xrm.Page.context.getUserId(); //Fetching user Id of current logged in user     var serverUrl = location.protocol + "//" + location.host + "/" + Xrm.Page.context.getOrgUniqueName();     var odataSelect = serverUrl + "/XRMServices/2011/OrganizationData.svc" + "/" + "TeamMembershipSet?$filter=SystemUserId eq guid'" + userId + "' and TeamId eq guid'" + teamid + "'";     var boolFlag = false;     $.ajax     (      {          type: "GET",          contentType: "application/json; charset=utf-8",          datatype: "json",            async: false,          url: odataSelect,            beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },          success: function (data, textStatus, XmlHttpRequest) {              if (data.d.results.length > 0) {
                 //alert(data.d.results[0].TeamId);
                 boolFlag = true;
             }
         },
 
         error: function (XmlHttpRequest, textStatus, errorThrown) {
             if (XmlHttpRequest && XmlHttpRequest.responseText) {
                 alert('OData Select Failed: ' + textStatus + errorThrown + odataSelect);
             }
         }
     }
    );
 
    return boolFlag;
    //return false; //Returing false if the user is not associated with the team
}
 
 
 
function DisableFormFields() {
    disableAttrs();
    RefreshGrids();
}
 
 
 
function RefreshGrids() {
 
    var opportunitySubgrids = Xrm.Page.getControl(function (ctrl, i) {
        if (ctrl.getControlType() == "subgrid") {
            return (ctrl);
        }
        else {
            return false;
        }
    });
 
    opportunitySubgrids.forEach(function (attribute, index) {
        var control = Xrm.Page.getControl(attribute.getName());
        if (control) {
            control.refresh();
        }
    });
 
 
 
}
 
function disableAttrs() {
    debugger;
    Xrm.Page.data.entity.attributes.forEach(function (attribute, index) {
        var control = Xrm.Page.getControl(attribute.getName());
        if (control && (control.getName() != "processid" && control.getName() != "stageid")) {
            control.setDisabled(true);
 
            //notification();
 
        }
    });
    Xrm.Page.ui.setFormNotification("The Form is Locked", "INFORMATION")
}
 
function tabdisable(tabname, disablestatus) {
    var tab = Xrm.Page.ui.tabs.get(tabname);
    if (tab == null) alert("Error: The tab: " + tabname + " is not on the form");
    else {
        var tabsections = tab.sections.get();
        for (var i in tabsections) {
            var secname = tabsections[i].getName();
            sectiondisable(secname, disablestatus);
        }
    }
}   // tabdisable
function sectiondisable(sectionname, disablestatus) {
    var ctrlName = Xrm.Page.ui.controls.get();
    for (var i in ctrlName) {
        var ctrl = ctrlName[i];
        var ctrlSection = ctrl.getParent().getName();
        if (ctrlSection == sectionname) {
            ctrl.setDisabled(disablestatus);
        }
    }
}  // sectiondisable

Please Feel Free to contact me if anyone face issues. The current Code requires that

Jquery and Json must be included in the form

Advertisements

Dynamics CRM Common Framework

I was asked to develop a framework that consist of common used java-script in dynamics CRM. I ll be sharing my findings in the code mentioned below

/**
Test Functions -- Start
**/

/***
// Method Name: testFunction
// Method Description:
// Created: Sept 04, 2015 04:09PM
// Author: Sabih Ahmed Khan
// param: testParam Desc: description of individual param goes here
// return bool Desc: Success or Failure
// Revisions: Example:Sue (2/19/2009) - Method Name - Changes done --REF:SUE_1
***/
function testFunction(testparam) {
    var testVar = testparam;

    //start:SUE_1
    testVar = false;
    //end:SUE_1

    return testVar;
}

/***
// Method Name: testFunctionAlert
// Method Description:
// Created: Sept 04, 2015 04:09PM
// Author: Sabih Ahmed Khan
// param: testParam Desc: sending param from the Entity
// return bool Desc: Success or Failure
// Revisions: 
***/
function testFunctionAlert(testparam) {
    alert(testparam);
    return true;
}

/**
Test Functions -- End
**/



/**
Conversion Functions -- Start
**/

/***
// Method Name: toUpperCaseAlpha
// Method Description: Convert the Alpha Text in to UpperCase in the Attribute
// Created: Sept 04, 2015 04:09PM
// Author: Sabih Ahmed Khan
// param: srcTxtAttribObj Desc: Attribute Object Pass
// return undefined Desc: N/A
// Revisions: 
***/
function toUpperCaseAlpha(srcTxtAttribObj) {
    //need to discuss with kashif in order to do upper case do we need to confirm the field type
    var attributeVal = srcTxtAttribObj.getValue();
    if (IsAlpha(attributeVal)) {
        if (attributeVal) {
            srcTxtAttribObj.setValue(attributeVal.toUpperCase());
        }
    }
    else {
        //need to discuss with kashif if any other than alphabetic case happens
        srcTxtAttribObj.setValue("");
    }
}


/***
// Method Name: toTitleCaseAlpha
// Method Description: Convert the Alpha Text in to Title Case in the Attribute
// Created: Sept 07, 2015 04:09PM
// Author: Sabih Ahmed Khan
// param: srcTxtAttribObj Desc: Attribute Object Pass
// return undefined Desc: N/A
// Revisions: 
***/
function toTitleCaseAlpha(srcTxtAttribObj) {
    var attributeVal = srcTxtAttribObj.getValue();
    if (IsAlpha(attributeVal)) {
        if (attributeVal) {
            srcTxtAttribObj.setValue(attributeVal.replace(/\w+/g, function (txt) {
                return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
            }
                                                                )
                                                                );
        }
    }
    else {
        //need to discuss with kashif if any other than alphabetic case happens
        srcTxtAttribObj.setValue("");
    }
}


/***
// Method Name: toDateFormat_DDMMYYY
// Method Description: Convert the date in to DD MM YYYY
// Created: Sept 07, 2015 04:09PM
// Author: Sabih Ahmed Khan
// param: srcDateAttribObj Desc: Attribute Object Pass
// return undefined Desc: N/A
// Revisions: 
***/
function toDateFormat_DDMMYYY(srcDateAttribObj) {
    var dateAttributeVal = srcDateAttribObj.getValue();
    if (dateAttributeVal) {
        var tempDateObj = new Date(dateAttributeVal || Date.now()),
            month = '' + (tempDateObj.getMonth() + 1),
            day = '' + tempDateObj.getDate(),
            year = tempDateObj.getFullYear();

        //not required
        /*if (month.length < 2) month = '0' + month;
        if (day.length < 2) day = '0' + day;*/
        dateString = [day, month, year].join('/');
        tempDateObj = new Date(dateString);
        srcDateAttribObj.setValue(tempDateObj);
    }
}


/**
Conversion Functions -- End
**/


/**
Validation Functions -- Start
**/


/***
// Method Name: IsAlpha
// Method Description: Tests if the value entered is Alphabetic either with space or not
// Created: Sept 04, 2015 04:09PM
// Author: Sabih Ahmed Khan
// param: srcTxtObj Desc: pass text obj
// return bool  Desc: true if matches the criteria
// Revisions: 
***/
function IsAlpha(srcTxtObjVal) {

    var AplhaRegEx = /^[a-zA-Z ]+$/; //regular expression for Alphabet Or Space Character

    if (AplhaRegEx.test(srcTxtObjVal)) {
        return true;
    }
    return false;
}

/***
// Method Name: IsAlphaNumeric
// Method Description: Tests if the value entered is Alphabetic or Numeric either with space or not
// Created: Sept 04, 2015 04:09PM
// Author: Sabih Ahmed Khan
// param: srcTxtObj Desc: pass text obj
// return bool  Desc: true if matches the criteria
// Revisions: 
***/
function IsAlphaNumeric(srcTxtObjVal) {

    var AplhaNumRegEx = /^[a-zA-Z][a-zA-Z0-9_\s]*$/; //regular expression for Alphabet Or Space Or Numeric Character

    if (AplhaNumRegEx.test(srcTxtObjVal)) {
        return true;
    }
    return false;
}


/***
// Method Name: IsNumeric
// Method Description: Tests if the value entered is Alphabetic or Numeric either with space or not
// Created: Sept 04, 2015 04:09PM
// Author: Sabih Ahmed Khan
// param: srcTxtObj Desc: pass text obj
// return bool  Desc: true if matches the criteria
// Revisions: 
***/
function IsNumeric(srcTxtObjVal) {

    var AplhaNumRegEx = /^[0-9]+$/; //regular expression for Numeric Character

    if (AplhaNumRegEx.test(srcTxtObjVal)) {
        return true;
    }
    return false;
}






/***
// Method Name: IsFieldExistsOnForm
// Method Description: Confirms if the field exists on form
// Created: Sept 07, 2015 04:09PM
// Author: Sabih Ahmed Khan
// param: fieldName Desc: pass field name
// return bool  Desc: true if Field Exists
// Revisions: 
***/
function IsFieldExistsOnForm(fieldName) {
    var fieldAttribute = Xrm.Page.getAttribute(fieldName);
    return fieldAttribute != null;
}

/***
// Method Name: IsSectionExistsOnForm
// Method Description: Confirms if the section exists on form
// Created: Sept 07, 2015 04:09PM
// Author: Sabih Ahmed Khan
// param: tabName, sectionName Desc: pass tab and section name
// return bool  Desc: true if Field Exists
// Revisions: 
***/
function IsSectionExistsOnForm(tabName, sectionName) {
    var section = Xrm.Page.ui.tabs.get(tabName).sections.get(sectionName);
    return section != null;
}

/***
// Method Name: IsTabExistsOnForm
// Method Description: Confirms if the section exists on form
// Created: Sept 07, 2015 04:09PM
// Author: Sabih Ahmed Khan
// param: tabName Desc: pass tab name
// return bool  Desc: true if Field Exists
// Revisions: 
***/
function IsTabExistsOnForm(tabName) {
    var tab = Xrm.Page.ui.tabs.get(tabName);
    return tab != null;
}


/**
Validation Functions -- end
**/




/**Utility Functions -- start
**/


/***
// Method Name: GetOptionSetText
// Method Description: Gets the option set Text
// Created: Sept 07, 2015 04:09PM
// Author: Sabih Ahmed Khan
// param: fieldName Desc: pass the field name
// return string  Desc: returns the option set Text Name
// Revisions: 
***/
function GetOptionSetText(fieldName) {
    if (IsFieldExistsOnForm(fieldName)) {
        var text = '';
        if (Xrm.Page.getAttribute(fieldName).getValue() != null) {
            text = Xrm.Page.getAttribute(fieldName).getSelectedOption().text;
        }
        return text;
    }
}

/***
// Method Name: GetLookupValueID
// Method Description: Gets the Look up Value ID
// Created: Sept 07, 2015 04:09PM
// Author: Sabih Ahmed Khan
// param: lookUpName Desc: pass the Look up Field Name
// return string  Desc: returns the lookupid
// Revisions: 
***/
function GetLookupValueID(lookUpName) {
    var name = '';
    var lookupid;
    var lookupObject = Xrm.Page.getAttribute(lookUpName);

    if (lookupObject != null) {
        var lookUpObjectValue = lookupObject.getValue();
        if ((lookUpObjectValue != null)) {
            name = lookUpObjectValue[0].name;
            lookupid = lookUpObjectValue[0].id;
        }
    }

    return lookupid;
}

/***
// Method Name: SetLookupValue
// Method Description: Sets the Look up Value for a particular Entity
// Created: Sept 07, 2015 04:09PM
// Author: Sabih Ahmed Khan
// param: lookUpName Desc: pass the Look up Field Name
// return string  Desc: returns the lookupid
// Revisions: 
***/
function SetLookupValue(lookup, name, id, entityType) {
    if (IsFieldExistsOnForm(lookup)) {
        var lookupid = null;
        var lookupObject = Xrm.Page.getAttribute(lookup);
        var value = new Array();
        value[0] = new Object();
        value[0].id = id;
        value[0].name = name;
        value[0].entityType = entityType;

        Xrm.Page.getAttribute(lookup).setValue(value);
    }
}

/***
// Method Name: GetFormType
// Method Description: get form type
// Created: Sept 07, 2015 04:09PM
// Author: Sabih Ahmed Khan
// param: N\A Desc: N\A
// return string  Desc: returns the form type
// Revisions: 
***/
function GetFormType() {
    var FormType = Xrm.Page.ui.getFormType();
    if (FormType != null) {
        switch (FormType) {
            case 1:
                return "create";
                break;
            case 2:
                return "update";
                break;
            case 3:
                return "readonly";
                break;
            case 4:
                return "disabled";
                break;
            case 6:
                return "bulkedit";
                break;
            default:
                return null;
        }
    }
}

/***
// Method Name: HideField
// Method Description: hides the field
// Created: Sept 07, 2015 04:09PM
// Author: Sabih Ahmed Khan
// param: fieldName Desc: field name that needs to be hidden
// return N/A  Desc: N/A
// Revisions: 
***/
function HideField(fieldName) {
    if (IsFieldExistsOnForm(fieldName)) {
        var fieldControl = Xrm.Page.ui.controls.get(fieldName);
        fieldControl.setVisible(false);
    }
}

/***
// Method Name: showField
// Method Description: shows the field
// Created: Sept 07, 2015 04:09PM
// Author: Sabih Ahmed Khan
// param: fieldName Desc: field name that needs to be hidden
// return N/A  Desc: N/A
// Revisions: 
***/
function showField(fieldName) {
    if (IsFieldExistsOnForm(fieldName)) {
        var fieldControl = Xrm.Page.ui.controls.get(fieldName);
        fieldControl.setVisible(true);
    }
}

/***
// Method Name: EnableField
// Method Description: Enable the field on the form
// Created: Sept 07, 2015 04:09PM
// Author: Sabih Ahmed Khan
// param: fieldName Desc: field name that needs to be enabled
// return N/A  Desc: N/A
// Revisions: 
***/
function EnableField(fieldName) {
    if (IsFieldExistsOnForm(fieldName)) {
        var fieldControl = Xrm.Page.ui.controls.get(fieldName);
        fieldControl.setDisabled(true);
    }
}


/***
// Method Name: DisableField
// Method Description: Disable the field on the form
// Created: Sept 07, 2015 04:09PM
// Author: Sabih Ahmed Khan
// param: fieldName Desc: field name that needs to be enabled
// return N/A  Desc: N/A
// Revisions: 
***/
function DisableField(fieldName) {
    if (IsFieldExistsOnForm(fieldName)) {
        var fieldControl = Xrm.Page.ui.controls.get(fieldName);
        fieldControl.setDisabled(false);
    }
}

/***
// Method Name: SetFocusField
// Method Description: Focus on the Field
// Created: Sept 07, 2015 04:09PM
// Author: Sabih Ahmed Khan
// param: fieldName Desc: field name that needs to be focused
// return N/A  Desc: N/A
// Revisions: 
***/
function SetFocusField(fieldName) {
    if (IsFieldExistsOnForm(fieldName)) {
        var fieldControl = Xrm.Page.ui.controls.get(fieldName);
        fieldControl.setFocus();
    }
}

/***
// Method Name: ShowTab
// Method Description: show the tab
// Created: Sept 07, 2015 04:09PM
// Author: Sabih Ahmed Khan
// param: tabName Desc: tab name that needs to be shown
// return N/A  Desc: N/A
// Revisions: 
***/
function ShowTab(tabName) {
    if (IsTabExistsOnForm(tabName)) {
        Xrm.Page.ui.tabs.get(tabName).setVisible(true);
    }
}

/***
// Method Name: HideTab
// Method Description: Hide the Tab
// Created: Sept 07, 2015 04:09PM
// Author: Sabih Ahmed Khan
// param: tabName Desc: tab name that needs to be hidden
// return N/A  Desc: N/A
// Revisions: 
***/
function HideTab(tabName) {
    if (IsTabExistsOnForm(tabName)) {
        Xrm.Page.ui.tabs.get(tabName).setVisible(false);
    }
}


/***
// Method Name: ShowSection
// Method Description: Show the section
// Created: Sept 07, 2015 04:09PM
// Author: Sabih Ahmed Khan
// param: tabName,sectionName Desc: tabName which contains the Section
// return N/A  Desc: N/A
// Revisions: 
***/
function ShowSection(tabName, sectionName) {
    if (IsSectionExistsOnForm(tabName, sectionName)) {
        Xrm.Page.ui.tabs.get(tabName).sections.get(sectionName).setVisible(true);
    }
}

/***
// Method Name: HideSection
// Method Description: Show the section
// Created: Sept 07, 2015 04:09PM
// Author: Sabih Ahmed Khan
// param: tabName,sectionName Desc: tabName which contains the Section
// return N/A  Desc: N/A
// Revisions: 
***/
function HideSection(tabName, sectionName) {
    if (IsSectionExistsOnForm(tabName, sectionName)) {
        Xrm.Page.ui.tabs.get(tabName).sections.get(sectionName).setVisible(false);
    }
}


/***
// Method Name: sectiondisable
// Method Description: Disable the Section
// Created: Sept 07, 2015 04:09PM
// Author: N/A
// param: tabName,sectionName Desc: tabName which contains the Section
// return N/A  Desc: N/A
// Revisions: 
***/
function sectiondisable(sectionname, disablestatus) {
    var ctrlName = Xrm.Page.ui.controls.get();
    for (var i in ctrlName) {
        var ctrl = ctrlName[i];
        var ctrlSection = ctrl.getParent().getName();
        if (ctrlSection == sectionname) {
            ctrl.setDisabled(disablestatus);
        }
    }
}

/***
// Method Name: setTodayDate
// Method Description: Function Moved Sets the Today Date
// Created: Sept 07, 2015 04:09PM
// Author: N/A
// param: dateFieldAttrib Desc: date field attribute to be passed in
// return N/A  Desc: N/A
// Revisions: 
***/
function setTodayDate(dateFieldAttrib) {
    var currentDate = new Date();
    dateFieldAttrib.setValue(currentDate);
}
/**Utility Functions -- end
**/