Xrm.Utility.lookupObjects to add records to a subgrid
Introduction
This post explains how to ‘re-wire’ the ‘Add Existing Court Orders’ button (Figure 1) to call a custom TypeScript function setDefaultView(). Within this function, the Xrm.Utility.lookupObjects client API is called. Figure 2 shows the ‘Lookup Records’ dialog which is generated when Xrm.Utility.lookupObjects is executed
Referring to the example in Figure 2, the Lookup Records dialog references records such as ‘Test Court Order 1’ via it’s entity reference.
entityType = "cpl_courtorder"
id = "{4936E866-F3AE-E11B-DD51-00E3A6AB3E9F}"
name = "Test Court Order 1"
In detail
lookupObjects Client API
The custom TypeScript function setDefaultView() defines the parameters which are sent to Xrm.Utility.lookupObjects() (Figure 3)
The TypeScript function associateAddExistingResults() displayed in Figure 4 (several lines down) would then add the selected record/s (i.e. the entity reference stored in the ‘results’ field) to the subgrid (the code for doing this isn’t listed in this post).
The function setDefaultView() is added to the court order ribbon (Figures 5 & 6). Note: Figure 5 shows the OOTB ‘Add Existing’ button being modified. A better approach would have been to create a new button. The reason being is that the court order subgrid could be placed on entities other than case review. In this case, the modified ‘Add Existing’ button wouldn’t work
Button Visibility
The ‘Add Existing’ button should only be displayed when it’s on a case review form. Below, is a description of how to achieve this using an ‘Enable Rule’ and JavaScript. Another option would have been to create a display rule (which runs on the server) and add a FormEntityContextRule step (see Appendix 2)
The TypeScript function (i.e. the visibilityRuleAddNewCourtOrderButton() in Figure 7) is required so to determine the visibility of the ‘Add Exisiting Court Orders’ button
This function (visibilityRuleAddNewCourtOrderButton()) is added to the court order ribbon
Appendix
1.) Hidden parameter
To see how Microsoft leverages Xrm.Utility.lookupObjects, it’s possible to use the browser debugger to view the file Main_system_library.js.
Referring to Figure 1, when the button ‘Add Existing Court Orders’ (the out of the box version) is pressed, it sets the ‘regarding’ attribute to the case review. It achieves this by using a hidden parameter called ‘createFromEntity’ (see below).
Xrm.Utility.lookupObject({
allowMultiSelect: true,
createFromEntity: currentEntity,
defaultEntityType: entityName,
entityTypes: [entityName],
lookupType: "Lookup.Simple"
});
2.) FormEntityContextRule
Referring to Figure 9, a couple of things to note:
- Un-Customised = False means that the button (the out of the box version) has customisation
- ‘Invert Result’ will, for example & unsurprisingly, invert a result from false to true
References
2.) Mastering Ribbon Workbench 2016 – Part 5 – Hiding buttons conditional to the form context