This one feature that I am going to pen down here, personally I have longing for it quite sometime now.
So before going into the HOW part of it, let’s understand the why part of it? When do I need show a Lookup dialog Programmatically? Well the answer is, numerous occasions. Like if you need to throw up a lookup dialog on change of field on the form OR you needed to throw the lookup dialog on click of a button on a web-resource.
All this time, we have achieved this but not in a supported way. Probably we may have ended up using Xrm.Internal.openDialog or some method of Mscrm.Internal namespace. But all these are unsupported and mere workaround to this perennial problem.
Well, no more messing around. Microsoft has finally brought in the Xrm.Utility.lookupObjects.
So let’s see how it works.
Let’s take a not so good example here. Let’s say whenever the account country is US, primary contact is mandatory and the user is thrown a lookup dialog of contacts from where he needs to select the Primary Contact. below if the function registered on change of country field
function changeOfCountry(e) ;
lookupOptions.allowMultiSelect = false;
lookupOptions.defaultEntityType = "contact";
lookupOptions.entityTypes = ["contact"];
function (result) );
Focus on the highlighted lines starting from top. The first is the lookupOptions paramter. Since we are going to open a contact, I have specified defaultEntityType and entityTypes both to contact.
Also you can set the defaultViewId and the viewIds property to show the default view to use and views to be available in the view picker respectively
For a complete set of the properties of lookupOptions refer to Microsoft Documentation. https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/clientapi/reference/xrm-utility/lookupobjects
As soon as the method is executed, the below dialog opens up
Cool isn’t it? Now half of the job is done. But how about getting the selected record back. Well this method does not disappoint you here either.
The success callback function returns the selected item as you can see from the code above.
It has properties of entityType, id and the name which you can use to set the look up field of any other type. Here I have used the same to set the value of primarycontactid field of the account record.
Such a huge sigh of relief for me.
Hope this helps!
Published at Mon, 04 Jun 2018 18:13:53 +0000