1
votes

I am trying to make a button on a form in Dynamics CRM, so that onClick the button show a dialog. The JS code I am using is as follows:

function addButton(attributename) {
if (document.getElementById(attributename) != null) {
    var sFieldID = "field" + attributename;
    var elementID = document.getElementById(attributename + "_d");
    var div = document.createElement("div");
    div.style.width = "19%";
    div.style.textAlign = "right";
    div.style.display = "inline";
    elementID.appendChild(div, elementID);
    div.innerHTML = '<button id="' + sFieldID + '"  type="button" style="margin-left: 4px; width: 100%;" ><img src="/_imgs/ico_16_4210.gif" border="0" alt="Dial this number"/></button>';
    document.getElementById(attributename).style.width = "80%";
    document.getElementById(sFieldID).onclick = function () {onbuttonclick(); };
  }
}

    function onbuttonclick() { alert('Hi');}

This function is written in a JS Web Resource which gets triggered with form onload event of contact entity. Whenever the form load event is triggered I get the following error in a dialog box:

There was an error with this field's customized event. Field:window Event:onload Error:undefined

kindly guide me towards the resolution. The code is taken from a sample example.

1
The example code you have is bad. The form should be accessed through the XRM object, not through the DOM. I suggest you have a look on MSDN for other examples. - Bvrce
what you want to do with this button? - Guido Preite
for now I just want to run this sample, i.e. onClick this should show a dialog box saying hi - pointer
What do your Handler Properties look like? - Vikram

1 Answers

0
votes

This simply means that you have an error somewhere in your JavaScript.

A much better solution would be to use a ribbon button, and have that ribbon button call javascript, instead of messing with the DOM (which is unsupported). drop the following code into your ribbondiffxml:

<Actions>
    <JavaScriptFunction Library="$[js library name]" FunctionName="[js function name]" />
</Actions>

Specifically, this should go into the CommandDefinitionNode.
Here is an example of what I do to open a dialog via javascript:

Ribbon.openDialogProcess = function (dialogId, EntityName, objectId) {
var url = Xrm.Page.context.getClientUrl() +
  "/cs/dialog/rundialog.aspx?DialogId=" +
  dialogId + "&EntityName=" +
  EntityName + "&ObjectId=" +
  objectId;
var width = 400;
var height = 400;
var left = (screen.width - width) / 2;
var top = (screen.height - height) / 2;
window.open(url, '', 'location=0,menubar=1,resizable=0,width=' + width + ',height=' + height + ',top=' + top + ',left=' + left + '');
}

so simply call that method in the RibbonDiffXML.