Archive for the ‘JavaScript’ Category

CRM by default doesn’t allow us to create our own custom fields using rich text or HTML, similar to the email Description out of the box. However, if we’re building forms that push data to a website dynamically, we may need the ability to build some HTML in CRM. In the past there’s been a few solutions available to do this in CRM. Some are more unsupported than others (e.g. hacking into a field on the form and converting it into a rich text editor).

One of the nicer solutions involves embedded a web resource on the form, and then taking the HTML generated by the web resource, and updating a field on the parent form. A good example of this, and the baseline of my solution is shown here, by Thomas Unzeitig:

This solution is using CKEditor, which is a tidy HTML/JavaScript based html editor, which means we can upload all of the web resources into a CRM solution and keep everything packaged nicely.

To download my solution, check out the project on CodePlex:

I have made the solution dynamic enough so that it can be dropped into any form by simply embedding the html editor web resource into the form, and passing in the field name to store the HTML data.

You can also set the Formatting to display the number of rows required, and to disable the iframe scrolling and border for a nicer look and feel. The HTML Editor will automatically expand to fill the space available inside the iframe, however big you choose to make it.

You can also pass a default value into the HTML editor, which will be applied when there is no existing value (e.g. for new records). This can be useful when you want to ‘guide’ users into entering the HTML in a specific format, rather than just letting them loose.

The default value needs to be encoded, and then included in the custom parameters of the web resource. You can get the encoded URL string from the following webpage by pasting in some HTML and then clicking ‘Encode’: Copy the encoded string and add it to the web resource parameters after the field value, e.g. field=new_html&defaultValue=%3Cb%3EHello%3C%2Fb%3E

The defaultValue parameter is optional, and if not specified, the HTML editor will simply display nothing initially.

Next we can preview our form and see that the html editor just works. We can see the default value being applied, including the ‘bold’ styling, and our basic editing tools are available.

The data from the HTML editor will be saved to the ‘HTML’ field every time you click out of the iframe. This means you don’t need to manually ‘save’ the HTML, it will just automatically keep up to date by itself. After we’ve saved the form, we can reload the page and the HTML editor will load up the HTML from our field automatically.

We can now hide that HTML field (as long as it remains on the form), and the HTML editor will continue to work and look pretty.

The buttons/editing tools available in this solution are based on the ‘Basic’ package provided by CKEditor. This is because the basic package seemed to meet our particular needs as we didn’t require a full blown HTML editor, just some basic rich text editing tools. This also means the entire solution is only 17 web resources.

If however you do require any additional editing tools, you can check out the CKEditor download page and create yourself a custom download package, and then just be sure to upload the missing web resources using the same publisher prefix, and same file names, then update the config.js file to load those plugins as well.

Note that this solution works in CRM 2013 as well as CRM 2015, and works on any entities. You can also add the HTML editor to the same form multiple times, each referencing different fields.

To download this package, check out the solution on CodePlex:

A common requirement is to open a dialog process from JavaScript on click of a command bar button etc. This is quite easy to do, simply using and passing in the right parameters to get the dialog working with the right record.

The problem is that this doesn’t allow us to run code when the dialog closes. We could use modal dialogs, but these are not supported in Chrome. Instead what I’ve done is created a manageable function for running a dialog, which allows us to run code when the dialog is closed.

To download the JavaScript library, check out the project on CodePlex:

It works by popping the dialog in a CRM light-box, which makes it look natural and seamless. When the dialog is closed, a callback function which we specify can be executed.

If the code runs inside outlook, where CRM light-boxes are not supported, a modal dialog is instead used, which still allows us to run our callback function when the dialog closes.

Call Dialog

Opens the specified dialog for a particular record in a CRM light-box, or Modal Dialog if run from Outlook. Once the dialog is closed, a custom callback function can be executed, e.g. to refresh the form with new data set by the dialog.

Parameters: Dialog ID/Guid, Entity Name, Record ID/Guid, Callback function, CRM Base URL (not required on forms/views)

Process.callDialog("C50B3473-F346-429F-8AC7-17CCB1CA45BC", "contact",,         
    function () {; 


To download the JavaScript library, check out the project on CodePlex:

In my previous blog post I introduced a new JavaScript library for calling processes, and I showed the function for calling a workflow. In this blog post I’m going to look at the function for calling an action.

Actions can be very useful when coupled with JavaScript, as it means we can execute complex server side logic, access fields from related records, or execute C# code using custom workflow activities right from within our JavaScript. The problem is, similar to calling workflows, we need to create a massive ugly SOAP request every time we want to call an action. With actions however, we also need to think about what parameters we’re passing to the action, and what output parameters we’re getting back.

For these reasons, it’s much easier to manage this in a library which we can easily call, and don’t have to worry about remembering the correct format for creating the requests.

To download the JavaScript library, check out the project on CodePlex:

Call Action

Calls the specified action and returns the response from the action asynchronously. Useful when needing to run C# code from web resources or command bar buttons when only JavaScript is available.

Parameters: Action Unique Name, Input Parameters (array), Success Callback (function), Error Callback (function), CRM Base URL (not required on forms/views)

Each Input Parameter object should contain key, value, and type. Types are defined by Process.Type enum. EntityReference values should be an object containing id and entityType.

The Success Callback function should accept 1 argument which is an array of output parameters, each containing key, and value

        key: "Target",
        type: Process.Type.EntityReference,
        value: { id:, entityType: "account" }
        key: "Input1",
        type: Process.Type.String,
        value: "Something"
    function (params) {
        // Success
        for (var i = 0; i < params.length; i++) {
            alert(params[i].key + "=" + params[i].value);
    function (e) {
        // Error


We can see the action here, which takes 1 string input parameter (plus the Target account reference, since this action isn’t global), and then returns 1 string output parameter. The output parameter includes the input parameter to prove that the action is receiving the input parameters correctly.

When the action is called, we can see the success callback function firing and alerting the output parameter, including the input parameter we passed to the action.

To download the JavaScript library, check out the project on CodePlex:

In a recent project I worked on, we needed to display a hyperlink in the form notification so that a user could click on it to open up an external webpage with parameters from the form. This proved to be a lot more difficult than initially anticipated, as CRM does not render any HTML tags that you pass into its setFormNotification function. This meant we needed some way of editing the HTML of the notification, which of course is unsupported. We also found that CRM re-renders the form notifications without warning when certain things happen, such as when the form is saved, or when additional notifications are added/removed. This meant any custom HTML was wiped randomly without any way to control it.

Because of these limitations, I decided to just create my own notification bar, using all the existing features available to the Xrm.Page.ui.setFormNotification SDK function, but also added a whole range of new features outlined below.

To download this package, check out the solution on CodePlex:


  • Any existing code using Xrm.Page.ui.setFormNotification and Xrm.Page.ui.clearFormNotification can easily be updated to use Notify.add and Notify.remove without the need to modify any parameters, and without any noticeable differences
  • Allows you to add buttons and/or hyperlinks into the notification, with custom JavaScript triggered on click
  • Supports additional icons, including SUCCESS, QUESTION, and LOADING
  • Supports custom HTML tags to be used manually in the notification message for greater flexibility
  • Ability to manually close a notification using the ‘X’ on the right hand side
  • Has smooth slide in and out transitions when adding and removing notifications
  • Ability to specify a duration after which that particular notification will disappear
  • Supports displaying notifications inside views from command bar buttons (only in web client – must specify duration)

Add Notification

Adds or overwrites a notification on the custom notification bar. Note that this notification bar is separate to the CRM Notification bar.

Parameters: Message, Icon, Unique ID, Buttons (array), Duration (seconds – optional)

All parameters are technically optional. If there’s no icon specified the icon will be removed. If the unique ID is not specified, the ID will be null (and any new notifications with no ID will overwrite that one). The buttons are optional and will display after the message in the order they are added to the array. Duration is optional, and if not specified the notification will only disappear if the user manually dismisses it or if other code removes it.

Supported Icon types are: “INFO”, “WARNING”, “ERROR”, “SUCCESS”, “QUESTION”, “LOADING”

Each button object in the array should have a ‘text’ to display on the button or hyperlink, a ‘callback’ function to call when the button or hyperlink is clicked, and optionally a ‘type’ of ‘link’ or ‘button’ (defaults to button if not specified)

Notify.add("Would you like to create a new Sale?", "QUESTION", "sale",
        type: "button",
        text: "Create Sale",
        callback: function () {
            Notify.add("Sale created successfully!", "SUCCESS", "sale", null, 3);
        type: "link",
        text: "Not now",
        callback: function () {


Remove Notification

This function removes one or all notifications from the custom notification bar. If an ID of a notification is passed to this function, that notification will be removed. If no ID is passed to this function, all notifications will be removed.

Parameters: Unique ID (optional)

// Remove a single notification

// Remove all notifications


To download this package, check out the solution on CodePlex:

In the past if you’ve needed to call a workflow from JavaScript, you need to build a massive XML SOAP request making sure to pass in the correct attributes and conditions to get the request working.

This is tedious and messy, especially when there are many places you need to do this in a solution. It’s also not good if something breaks in the future and you need to go back and fix up all instances of where the code is being used.

For these reasons, I’ve created a JavaScript library to simplify calling processes, and to make the code manageable going forward. But most of all, it’s so I don’t have to keep finding the correct way to build the SOAP requests!

This library includes functions for calling workflows, actions, and even popping dialogs. For this blog post, I’ll just look at calling workflows. I’ll cover calling actions and dialogs in other posts.

To download the JavaScript library, check out the project on CodePlex:

Call Workflow

Runs the specified workflow for a particular record asynchronously. Optionally, you can add callback functions which will fire when the workflow has been executed successfully or if it fails.

Parameters: Workflow ID/Guid, Record ID/Guid, Success Callback (function), Error Callback (function), CRM Base URL (not required on forms/views)

    function () {
        alert("Workflow executed successfully");
    function () {
        alert("Error executing workflow");

CRM 2013 introduced light-boxes for most popups to make the UI look cleaner with less browser alerts and popups. However, these internal functions were not included in the SDK, so as developers we couldn’t access them for our custom code. Instead, we’ve been forced to use alertDialog and confirmDialog which under the hood just calls the browsers alert and confirm functions.

The main problems with this is that we cannot customize the buttons, and the alerts look ugly.

What I’ve done is created a custom JavaScript library to allow us to create our own light-box popups which look natural and part of CRM. We can now create our own seamless alerts and popups using custom buttons and custom callback functions for each button. We can also specify different types of icons to display in the alerts, instead of being forced to use the alert ‘exclamation mark’ or confirm ‘question mark’.

While technically unsupported, this code is manageable if it ever does break in future CRM releases, so it will be as simple as updating the solution files and everything will just work. In the event that the CRM Lightbox doesn’t work or isn’t supported (like in outlook), a modalDialog will be displayed.

How it Works

Download and install the unmanaged solution from CodePlex:, then simply add a reference to mag_/js/alert.js wherever you want to use the custom alerts. This will work from forms, views, command bars, and pretty much anywhere in CRM that supports JavaScript.

Next simply call the function. All other dependent web resources will be loaded automatically.

Parameters: Title (main message), Subtitle (smaller message), Buttons (array), Icon, Width (px), Height (px), CRM Base URL

All the parameters are technically optional. If no buttons are specified, a default ‘OK’ button with no callback will be added. If no icon is specified, then no icon will be displayed. If height is not specified, it will default to 225. If width is not specified it will default to 450. The URL only needs to be specified if the alert is being called from somewhere that doesn’t have Xrm.Page access (e.g. web resource).

Each button object in the buttons array needs to have a ‘label’ (text displayed on the button), and optionally a ‘callback’ (function called if the button is clicked).

The following icons are supported: “INFO”, “WARNING”, “ERROR”, “SUCCESS”, “QUESTION”."Would you like to create a new Sale?", null,
        label: "Create Sale",
        callback: function () {
  "Sale created successfully!", null, null, "SUCCESS", 500, 200);
        label: "Not now"
    }], "QUESTION", 500, 200);


To download this package, check out the solution on CodePlex:

Previously I’ve been posting about how to recreate CRM functionality using browser bookmarkets. These have included useful functions like opening advanced find, or publishing customizations. In this blog post I’m going to go one step further and show how we can completely disable ALL client side validation on a form so that we can make changes to a form without worrying about field requirement levels, visibility, business rules, or JavaScript.

What I’m about to show is intended for testing purposes only, and should not be used in any production environments – otherwise you might end up with dirty data in your system. So use it cautiously, and use it wisely!

What it does:

  • Makes all required fields not required.
  • Makes all hidden fields visible.
  • Enables all disabled fields.
  • Makes all hidden tabs visible.
  • Makes all hidden sections visible.
  • Expands all collapsed tabs.
  • Clears field notifications on all fields.
  • Prevents JavaScript from firing on save.
  • Allows editing of inactive records.

One click of this button and you instantly have edit access to every field added to your form. This is extremely useful when you have JavaScript or plugins setting or relying on hidden fields on your form, and you need to quickly get in and see or modify those fields.

It’s also useful if you need to change a value on a form without entering in all the required fields – particularly as an admin when you need to fix up 1 or 2 fields on an existing record without filling out the rest of the required fields.

I’ve set up a form as an example below.

You can see we have most fields disabled. What you can’t see are the hidden fields and sections. Also when we try to save the form, our CRM Admin has added some “secure” JavaScript to prevent us from saving the form:

One click of our magic ‘God Mode’ button, and voila!

As you can see, literally every field is now unlocked, and not required. We can also see the ‘Company’ field in the second column which was previously hidden, the entire ‘Hidden’ tab is now visible, and we can edit any of the values (with the exception of Status, Created On, and Created By which can be changed but do not save to the database). We can also now save the form and bypass that pesky on save validation, and even clear the value of required fields.

Further down what you can’t see in the screenshot is that our Details tab has now been expanded as well. This means if we need to find a field we can Ctrl + F and quickly find what we’re looking for even if it was in a collapsed tab.

One other unexpected feature of this button is that we can also open an inactive record, turn on God Mode, and then change any of the ‘disabled’ fields. We can then simply navigate away from the record and the changes will be saved to the inactive record! (Only works with autosave enabled, or if you have rollup 1 or lower, and doesn’t work on activity entities).

Any user can set up this button for their own personal use, and it can be used with any CRM 2013 system, on any modern entity, and you don’t need any additional CRM security roles/privileges. To configure the bookmarklet, simply create a new bookmark, then edit the properties and set the URL to the following script:

javascript:var form=$("iframe").filter(function(){return $(this).css("visibility")=="visible"})[0].contentWindow;try{form.Mscrm.InlineEditDataService.get_dataService().validateAndFireSaveEvents=function(){return new Mscrm.SaveResponse(5,"")}}catch(e){}var;for(var i in attrs){attrs[i].setRequiredLevel("none")}var contrs=form.Xrm.Page.ui.controls.get();for(var i in contrs){try{contrs[i].setVisible(true);contrs[i].setDisabled(false);contrs[i].clearNotification()}catch(e){}}var tabs=form.Xrm.Page.ui.tabs.get();for(var i in tabs){tabs[i].setVisible(true);tabs[i].setDisplayState("expanded");var sects=tabs[i].sections.get();for(var i in sects){sects[i].setVisible(true)}}


If you’re a CRM admin/developer reading this, you probably want to think about what validation you’re doing on the client side and consider moving anything critically important into server side validation.

In Dynamics CRM 2013, when auto save is enabled, any changes to a record will be saved automatically when you close the record. In some cases we need to change data on a record to test functionality, and so we don’t always want those changes to be saved.

I’ve created a browser bookmarklet which will disable auto save for the record you have open, so that if you ever need to enter some test data into a record, you can simply click the bookmark which will prevent the system from automatically saving the form every 30 seconds, and also when you close the record or navigate away.

What the script does is it attaches an onsave event which checks the save mode, and cancels the save event for anything other than a physical ‘Save’, which can only be triggered by the little save icon in the bottom right corner (or my save bookmarklet). Any other type of save, including auto save and save and close, will be prevented. When you close the record or navigate away with unsaved changes, you will be prompted that there are unsaved changes just like it would if auto save was disabled for the organisation.

As you can see above, I’ve clicked the ‘Disable Auto Save’ bookmarklet, then made some changes to the Account Name, and when we navigate away we’re prompted that changes have not been saved. We can then simply click ‘Ok’ to close the form without saving the changes. The next time we open the record, or when we open any other record, auto save will be enabled again until. This allows us to turn off auto save only when required.

The script to use for this bookmark is as follows:

javascript: var frame = $("iframe").filter(function () { return ($(this).css('visibility') == 'visible') }); frame[0]{ if (context.getEventArgs().getSaveMode() != 1) { context.getEventArgs().preventDefault(); } });

In Dynamics CRM 2013 Customizers and Admins no longer have the ‘Customize’ tab on records anymore, which I often found useful for when we need to quickly get in and customize an entity, and then once done come back to the record and publish customizations.

To make things a little easier again, I’ve added these buttons back as browser bookmarklets. This will allow us to quickly and easily launch into the default solution, and automatically navigate us to the entity we’re on. We can also use this from other areas of the system, including views and dashboards, allowing us to jump straight into the customizations area without having to navigate through settings and losing our place in CRM.

I’ve also added a Publish button which can be used from anywhere in the system, including inside a solution and on a form. This will publish all customizations, and will be useful in times where there is no publish button available, for example when you edit a form and ‘Save & Close’ – you can now simply click the Publish bookmarklet to publish those changes instead of having to reopen the form or solution to publish.

The scripts to use for both of these bookmarks are as follows:


javascript: var frame = $("iframe").filter(function () { return ($(this).css('visibility') == 'visible') }); var form = frame[0].contentWindow; try { var etc = form.Xrm.Page.context.getQueryStringParameters().etc; } catch(e) {} form.Mscrm.RibbonActions.openEntityEditor(etc);



javascript: var frame = $("iframe").filter(function () { return ($(this).css('visibility') == 'visible') }); frame[0].contentWindow.Mscrm.FormEditor.PublishAll();

In a previous blog post of mine I explained how to add Advanced Find onto the Form Command Bar in CRM 2013, since the list view no longer stays open while on forms like they did in 2011, it can be difficult getting to advanced find sometimes.

In this blog post I will be taking the code from that blog post and converting the button into a browser bookmarklet so that we can launch advanced find from anywhere in CRM, including forms, views, dashboards, and solutions.

Just like the command bar button, this bookmarklet will automatically open advanced find to the entity you’re on if coming from a form or view, otherwise it will display the first entity by default.

The script for the bookmark is as follows:

javascript: var frame = $("iframe").filter(function () { return ($(this).css('visibility') == 'visible') }); var form = frame[0].contentWindow; var u = form.Mscrm.CrmUri.create("/main.aspx"); u.get_query()["pagetype"] = "advancedfind"; try { var etc = form.Xrm.Page.context.getQueryStringParameters().etc; } catch (e) { } if (etc) { u.get_query()["extraqs"] = "EntityCode=" + etc; } form.openStdWin(u, "_blank", 900, 600); void (0);


As you can see, from a contact form the Advanced Find bookmarklet opens a new window with advanced find defaulted to Contacts.

Now you don’t have to think about where you need to be to launch advanced find, as long as you’re inside CRM when you click the button it should take you right where you need to go!