Attaching Javascript code to a tool bar button can be very ugly. Generally the code needs to be included within the CRM, ISV Config XML file. It’s pretty easy to add a button via the ISV Config. Click Here for more information on adding custom buttons to a Microsoft Dynamics CRM Entity form, toolbar.
The red highlighted Javascript tag below shows you where you would typically place your JavaScript or JavaScript function call but this isn’t the best place for the JavaScript. I have seen huge JavaScript routines embedded in to the tag whci makes debugging and readability a painful exercise. Even if you call a JavaScript function and leave the tag nice and cleas as shown here that Javascript function has to be maintained outside of the CRM Model.
<Entities>
<Entity name=”new_customentity”>
<ToolBar ValidForCreate=”0″ ValidForUpdate=”1″>
<ToolBarSpacer></ToolBarSpacer>
<Button Icon=”/_imgs/ico_18_debug.gif” JavaScript=” DuplicateRecord (10016);”>
<Titles>
<Title LCID=”1033″ Text=”Duplicate Record” />
</Titles>
<ToolTips>
<ToolTip LCID=”1033″ Text=”Copies a record based on this open record.” />
</ToolTips>
</Button>
<ToolBarSpacer />
</ToolBar>
</Entity>
</Entities>
The solution is pretty simple.
If we change the structure of our JavaScript function a bit we can simply place it in a Entity’s form OnLoad Event. The key syntax is simply MyFunction = function() .
Here is a working example of a function I wrote which calls a web service to copy the current open record and create a new one based on it,
The CRM Form OnLoad Event JavaScript
DuplicateRecord = function() {
try { var oXmlHTTP = new ActiveXObject(“Msxml2.XMLHTTP”); oXmlHTTP.Open(“POST”, “/somepath/ DuplicateRecord Service.asmx/ DuplicateRecord?mso-spacerun: yes”> + crmForm.ObjectId, false); oXmlHTTP.setRequestHeader(“Content-Type”, “application/x-www-form-urlencoded”) oXmlHTTP.Send(‘jobId=’ + crmForm.ObjectId); var newId = oXmlHTTP.responseXML.selectSingleNode(“string”).text; } catch (e) { debugger; return null; } }
The ISV Config XML Tag
<Button Icon=”" Url=”" PassParams=”1″ WinParams=”" WinMode=”0″ JavaScript=” DuplicateRecord ();”> <Titles> <Title LCID=”1033″ Text=” Duplicate This Record ” /> </Titles> <ToolTips> <ToolTip LCID=”1033″ Text=”Copy Record” /> </ToolTips> </Button>Conclusion
I like this approach because now all our JavaScript is still maintained within the CRM Entity’s and for a number of good reasons that’s where a Microsoft Dynamics CRM application should store the JavaScript. Because its with the entity it will get exported with your model and other customizations.
