Useful javascript tricks for Dynamics CRM 2011

on

I have used Dynamics CRM 2011 for more than a year, and although I like it there are certain things that can make your head explode if you don’t know how to work around them. Here is my personal compendium of code and tricks I have made this past year with Antonio Romera, hopefully it will help you while working with this awesome software.

For starters

First I have to tell you that you must have a basic understanding of how Dynamics CRM 2011 works and how to add your own javascript code.
First I recommend you add jQuery to you web resources. You might never use it but it is a really good tool to have whenever you need the extra help. You can download jQuery here. We use jQuery 1.x since we need support for Internet Explorer 6, 7, or 8 in our company.
To add new web resources go to your solution and there should be a Web Resources tab. Click new and paste the code from the webpage above.

How to debug your code

OMG I lost so much time with this one. I’m used to use console.log() to debug my JS code, but you can’t use that nifty little function in Dynamics CRM 2011. So we use another nifty little function called debugger. You can just add it at the beginning of your code and it will load a debugging window. I use MS Visual Studio for the debugging since I like the new interface, but there should be different options.
But remember to change your debugging setting for IE. Go to Tools > Internet Options > Advanced and uncheck the two “Disable script debugging” check boxes that are checked by default in IE.
crm1

How to get info from your fields in JS

I made a little test.js file to look at how everything works. It has helped me a lot to understand Dynamics CRM 2011 client side better and I hope it does the same for you.


/*Just to test that alert works and how the alert interacts with everything*/
var alertTest = function(){
    alert("Sup, I'm a test");
};

/*Test a parameter output. Use debugger instead*/
var textTest = function(parameter){
    alert("Stop sending: " + parameter);
};

/*Get a feeling of how to call a function in an entity*/
var varTest = function(name){
    alert("Hello my name is: " + name + " and I say " + Xrm.Page.getAttribute(name).getValue());
};

/*Get the value of a field*/
var contextTest = function(context){
    alert("Context is: " + context.getEventSource().getValue());
};

/*Sad day. But use debugger instead*/
var consoleTest = function(){
    /*Doesnt work :´(*/
    console.log("Please baby work");
};

/*Get the text of a label*/
var getLabel = function(context){
    alert( Xrm.Page.getControl(context.getEventSource().getName()).getLabel() );
};

/*Get the value of a lookUp*/
var getLookupValue = function(context){
    var object = context.getEventSource().getValue();
    alert("My value is: " + object[0].name);
    alert("My guid is: " + object[0].id);
};

/*Get the value of a picklist*/
var getPicklistValue = function(context){
    alert(context.getEventSource().getSelectedOption().text);
};

/*Get the value from a CRM field*/
var varMyValue = Xrm.Page.getAttribute(“CRMFieldSchemaName”).getValue() ;

/*Set the value of a CRM field*/
Xrm.Page.getAttribute(“po_CRMFieldSchemaName”).setValue(‘My New Value’);

/*Hide/Show a tab/section*/
Xrm.Page.ui.tabs.get(5).SetVisible(false);
Xrm.Page.ui.tabs.get(5).SetVisible(true);

/*Call the onchange event of a field*/
Xrm.Page.getAttribute(“CRMFieldSchemaName”).fireOnChange();

/*Get the selected value of picklist*/
Xrm.Page.getAttribute(“CRMFieldSchemaName”).getSelectedOption().text;

/*Set the requirement level*/
Xrm.Page.getAttribute(“CRMFieldSchemaName”).setRequiredLevel(“none”);
Xrm.Page.getAttribute(“CRMFieldSchemaName”).setRequiredLevel(“required”);
Xrm.Page.getAttribute(“CRMFieldSchemaName”).setRequiredLevel(“recommended”);

/*Set the focus to a field*/
Xrm.Page.getControl(“CRMFieldSchemaName”).setFocus(true);

/*Stop an on save event*/
event.returnValue = false;

/*Return array of strings of users security role GUIDs:*/
Xrm.Page.context.getUserRoles()

/*Hide/Show Tabs and Sections*/
function setVisibleTabSection(tabname, sectionname, show) {
    var tab = Xrm.Page.ui.tabs.get(tabname);
    if (tab != null) {
        if (sectionname == null)
            tab.setVisible(show);
        else {
            var section = tab.sections.get(sectionname);
            if (section != null) {
                section.setVisible(show);
                if (show)
                    tab.setVisible(show);
            }
        }
    }
}

If you are totally new this examples should give you a rough guideline of how to use JS in Dynamics CRM 2011. Also if you come from Dynamics 4 this app will help you a lot to translate from both versions.

Get that business unit

Security is a big role for any software. And you might want (must want really) to protect sensible information from being leaked. If you use Dynamics Business Units you can add this layer of security to your JS code with the following code.


function GetBusinessUnit(){
 var request = "" +
    "" +
    "" +
    "WhoAmI" +
    "";
    var resultXml = XrmServiceToolkit.Soap.Execute(request);
    var buid = resultXml.getElementsByTagName("a:Results")[0].childNodes[1].childNodes[1].text;
    var cols = ["name"];
    var retrievedContact = XrmServiceToolkit.Soap.Retrieve("businessunit", buid, cols);
    var businessUnitName = retrievedContact.attributes['name'].value;
    alert(businessUnitName);
}

function GetMyBusinessUnit() {
    var xml = "" +
    "" +
    "" +
    GenerateAuthenticationHeader() +
    "" +
    "" +
    "" +
    " <fetch mapping='logical' count='1'>" +
    " <entity name='businessunit'>" +
    " <attribute name='name' />" +
    " <filter>" +
    " <condition attribute='businessunitid' operator='eq-businessid' />" +
    " </filter>" +
    " </entity>" +
    " </fetch>" +
    "" +
    "" +
    "" +
    "";

    var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
    xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
    xmlHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Fetch");
    xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
    xmlHttpRequest.send(xml);

    var resultXml = xmlHttpRequest.responseXML;

    var resultSet = resultXml.text;
    resultSet.replace('<', '< ');
    resultSet.replace('>', '>');

    var oXmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    oXmlDoc.async = false;
    oXmlDoc.loadXML(resultSet);

    var result = oXmlDoc.getElementsByTagName('name');

    return result[0].text;
}

Fill that pesky Picklist with Words not numbers

This is just a simple hack to populate a picklist with words instead of numbers. This is just a personal headache since I had a lot of options!


var addPicklistOption = function (_value, _options, _picklist) {
    for (i = _options.length - 1; i >= 0; i--) {
        if (_options[i].text === _value) {
            _picklist.addOption(_options[i]);
            break;
        }
    }
};

/*Example*/
var addGrade = function () {
    var picklist_up_grade = Xrm.Page.getControl('grade');
    var picklist_up_grade_Attribute = Xrm.Page.getAttribute('grade');
    var _gradeOptions = picklist_up_grade_Attribute.getOptions();

    /*Clean the picklist*/
    picklist_up_grade.clearOptions();

    /*Add a grade*/
    addPicklistOption("1°", _gradeOptions, picklist_up_grade);
};

The End

Well that’s all for now folks. I’ll add more tips and tricks as life goes on and problems keep getting solved. Leave your comments below if I’m doing something wrong, if you have a tip you want to add or just to say hi.

  • Jared Moore

    Just wanted to say thank you for compiling this blog of great tricks and tips for CRM. I used some of them today to solve a need in my company. Your work is appreciated!

    • Robaum

      Thank you so much Jared!