Monday, May 03, 2010

MSCRM 4.0: Adding a Button to a Form Toolbar using Client Script

Usually we add custom button to CRM form through ISV.config customization, but there could be scenarios that you may want to add button on-fly in the form’s onLoad event. Here is the script that just does this job.
 * Add a Button to a CRM4.0 form toolbar using client script.
 * @author Daniel Cai,
function createToolbarButton(btnTitle, btnId, clickAction, imagePath, btnLabel, includeSpacer) {
    var toolbar = document.all.mnuBar1.rows(0).cells(0).childNodes[0];
    var html = (!includeSpacer) ? '' : '<li class="ms-crm-Menu-Spacer" tabIndex="-1">&nbsp;<img style="clip: rect(0px 4px 17px 0px); background-image: url(/_imgs/imagestrips/control_imgs_1.gif); width: 4px; background-position-y: -55px; height: 17px" alt="" src="/_imgs/imagestrips/transparent_spacer.gif"></li>';
    html += '<li id="' + btnId + '" + class="ms-crm-Menu" title="' + btnTitle + '" tabIndex="-1" onclick="window.execScript(action)" action="' + clickAction + '">';
    html += '<span class="ms-crm-Menu-Label"><a class="ms-crm-Menu-Label" tabIndex=-1 onclick="return false;" href="javascript:onclick();" target=_self>';
    html += (!imagePath) ? '' : '<img class="ms-crm-Menu-ButtonFirst" tabIndex="-1" alt="' + btnTitle + '" src="' + imagePath + '" />';
    html += '<span class="ms-crm-MenuItem-TextRTL" tabIndex=0>' + btnLabel + '</span></a></span>';
    toolbar.insertAdjacentHTML("beforeEnd", html);
To call the script, you may simply do this:
createToolbarButton("Test button", "mybuttonid", "myfunc()", "/_imgs/ico_16_4200.gif", "Test button label", true);
The code looks a little messy due to its lengthy html code, but once you have pasted to your file, it shouldn't look too bad. :-)

The parameters that the function accepts are all self-explanatory, hope you can figure out without requiring much explanation.

By the way, this is a re-post of my response to a question on CRM Development Forum.



  1. Your code is stolen without any reference to your blog.

  2. Thanks Andriy for the information. I guess we can't do much about it, I hope it could help his life easier.

    BTW, I totally misunderstood your comment at first sight.

    Thanks Andriy!

  3. very nice code yar.....

    Good work.....

  4. Hi, I put my code to the function myfunc () but does not work. The function I put in the OnLoad event. I hope you can help me. Thanks.

  5. @edudebolivar, you could try to define your function in the following fashion:

    myfunc = function() {


    window.myfunc = function() {

    Hope it helps.

  6. Thanks a lot, now run my code. Happy new year !!!

  7. Wow great information about toolbar development. Hire toolbar developer exhaustive analysis is capable of reshaping toolbar solutions with accuracy and precision. Here, cutting-edge technology in collaboration with cost-efficient methods is the stand-out corner for toolbar developer.