Code Modularity. Abstraction. Encapsulation. Readability. Maintainability. These are just words we use during job interviews! They’re certainly not applicable to JavaScript – a SCRIPTING language, where we are almost compelled to write whatever we want, quickly, as long as it works right now, right?

Ok, maybe. But once in a while, an opportunity presents itself to create a logical firewall for yourself, and clean things up just a bit. The Microsoft Xrm.Page object model presents just such an opportunity.

Most of the JavaScript code I’ve seen embeds the calls to Xrm.Page directly in the JavaScript. Resulting in code that looks something like this:

It’s a little hard to read. It’s a little hard to tell quickly what it’s doing. But what if it said:

Or better yet, just do the existence check inside the GetOptionSetText call and have your functional Javascript look like:

Which brings me to my point. Create an XrmPageCommonLibrary.js file that contains all your Xrm.Page calls, and add it as a Web Resource to any of your forms where you want to make calls to the Xrm.Page object model.  If it’s not immediately obvious how useful this is, here are some ways you may find it helps:

  1. Solve the problem of how to get values for different attribute types (fields, option sets, lookups) once. Reuse that solution. (Modularity)
  2. Solve the problem of null checking in one place to avoid Null Object Reference errors (Abstraction)
  3. Clean up your code. Never refer to the Xrm.Page object model outside of your Common Library (Encapsulation)

So, try creating an XrmPageCommon library, and show it to your tech lead. Be sure to use words like Modularity, Encapsulation, and Maintainability.  You can thank me later.

I’ve included some of the actual functions out of my common library below, along with a list of some of the others you might create.  The first two are really useful for embedding in your other function calls to keep them from throwing errors when your users start removing attributes off your forms without telling you.

Not that THAT ever happens:

Here are some other functions you might want to write:

ShowField

HideField

EnableField

DisableField

GetFieldValue

GetFieldControl

GetFieldLabel

SetFieldValue

SetLookupValue

SetFieldRequirementLevel

AlwaysSubmit

SetFocus

RemovePicklistItemByName

AddPicklistItem

PicklistItemExists

Like this post? Share it!