Mastering Lookup Controls in Dynamics 365 with Client API methods

In the vast world of Dynamics 365, customizing the behavior of lookup controls using JavaScript can significantly enhance user interaction and data integrity. In this blog, we delve into four powerful client API methods that transform how lookup controls operate, ensuring they cater precisely to business needs. Through real-life examples and practical code snippets, we’ll explore how these methods can be utilized to refine user experience and streamline processes.


1. Pre-search Filtering with addPreSearch

The addPreSearch method allows you to add client-side filtering to lookup dialogs before they are rendered. This method is invaluable when you need to restrict lookup results based on specific criteria that aren’t captured by default filters or when those criteria are dynamically changed based on other data points on the form.

Imagine a scenario where you only want to show contacts from the same city as the company of the current record. Using addPreSearch, you can inject a custom filter to achieve this dynamically.

Code Example:

function preFilterLookup(executionContext) {
    var formContext = executionContext.getFormContext();
    formContext.getControl("contactid").addPreSearch(function () {
        var city = formContext.getAttribute("city").getValue();
        var fetchXml = "<filter type='and'><condition attribute='address1_city' operator='eq' value='" + city + "' /></filter>";
        formContext.getControl("contactid").addCustomFilter(fetchXml);
    });
}

2. Custom Filtering with addCustomFilter

The addCustomFilter method allows adding custom fetchXML filter criteria to the lookup query. This method is crucial for applying complex and specific filtering logic that cannot be predefined in the system.

Consider a case where you need to filter contacts based on a custom attribute or a combination of attributes that change based on business logic, such as filtering contacts who are marked as ‘VIP’ for specific high-value transactions.

Code Example:

function applyCustomFilter(executionContext) {
    var formContext = executionContext.getFormContext();
    var filter = "<filter type='and'><condition attribute='new_vip' operator='eq' value='1' /></filter>";
    formContext.getControl("contactid").addCustomFilter(filter, "contact");
}

3. Adding Custom Views with addCustomView

The addCustomView method is used to add a custom view to the lookup field. This is particularly useful when the standard views do not meet the user’s needs, or you need to present data that is tailored to specific circumstances, such as during a marketing campaign.

Assume you have a lookup field named accountid on the form, and you want to add a custom view that filters accounts based in New York and displays specific columns.

Code Example:

function addCustomViewToLookup(executionContext) {
    var formContext = executionContext.getFormContext();
    var lookupControl = formContext.getControl("accountid");

    // Define the custom view ID
    var viewId = "00000000-0000-0000-0000-000000000001";

    // Define the entity name
    var entityName = "account";

    // Define the view display name
    var viewDisplayName = "New York Accounts";

    // Define the fetchXml query to filter accounts based in New York
    var fetchXml = `
        <fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">
            <entity name="account">
                <attribute name="name" />
                <attribute name="telephone1" />
                <attribute name="primarycontactid" />
                <attribute name="accountid" />
                <order attribute="name" descending="false" />
                <filter type="and">
                    <condition attribute="address1_stateorprovince" operator="eq" value="NY" />
                </filter>
            </entity>
        </fetch>`;

    // Define the layoutXml to specify which columns to display
    var layoutXml = `
        <grid name="resultset" object="1" jump="name" select="1" icon="1" preview="1">
            <row name="result" id="accountid">
                <cell name="name" width="300" />
                <cell name="telephone1" width="150" />
                <cell name="primarycontactid" width="150" />
            </row>
        </grid>`;

    // Define whether this view should be the default view
    var isDefault = true;

    // Add the custom view to the lookup control
    lookupControl.addCustomView(viewId, entityName, viewDisplayName, fetchXml, layoutXml, isDefault);
}

// Register the addCustomViewToLookup function to the form's OnLoad event
function formOnLoad(executionContext) {
    addCustomViewToLookup(executionContext);
}

4. Handling Click Events on Lookup Tags with addOnLookupTagClick

The addOnLookupTagClick method provides the ability to handle click events on the tags in the lookup field. This enhances the interactivity of lookup fields by allowing custom actions, such as opening related records or displaying additional details in a dialog.

Assume you have a lookup field named contactid. When a user clicks on the lookup tag, an alert will display the name, ID, and entity type of the selected contact.

Code Example:

function onLookupTagClick(executionContext) {
var formContext = executionContext.getFormContext();
formContext.getControl("contactid").addOnLookupTagClick(function(context) {
var tagValue = context.getEventArgs().getTagValue();
// Dis// Function to handle the click event on the lookup tag
function onLookupTagClick(executionContext) {
var eventArgs = executionContext.getEventArgs();
var tagValue = eventArgs.getTagValue();

if (tagValue) {
var tagName = tagValue.name;
var tagId = tagValue.id;
var tagEntityType = tagValue.entityType;
var tagFieldName = tagValue.fieldName;

alert("Lookup Tag Clicked:\n" +
"Name: " + tagName + "\n" +
"ID: " + tagId + "\n" +
"Entity Type: " + tagEntityType + "\n" +
"Field Name: " + tagFieldName);
} else {
alert("No tag value found.");
}
}

// Function to initialize and add the onClick handler
function initializeLookupTagClick(executionContext) {
var formContext = executionContext.getFormContext();
var lookupControl = formContext.getControl("contactid");

if (lookupControl) {
lookupControl.addOnLookupTagClick(onLookupTagClick);
}
}

// Register the initialize function to the form's OnLoad event
function formOnLoad(executionContext) {
initializeLookupTagClick(executionContext);
}play custom dialog or navigation
showContactSummary(tagValue);
});
}

5. Dynamically Setting Entity Types for Lookup Controls with setEntityTypes

The setEntityTypes method is an essential tool for developers working with Dynamics 365. It allows you to dynamically set the entity types that users can select from when using a lookup field. This method is particularly useful in scenarios where the available entity types need to change based on other data or user selections on the form.

Imagine a scenario where you need to link either contacts or accounts to a custom entity based on the type of transaction being processed. For sales-related activities, you might want only account entities to be selectable, whereas for service requests, contact entities might be more appropriate. The setEntityTypes method allows you to tailor the lookup experience on the fly, ensuring users can only select the most relevant entity types, thereby simplifying data entry and reducing errors.

Code Example:

function adjustLookupOptions(executionContext) {
var formContext = executionContext.getFormContext();
var transactionType = formContext.getAttribute("new_transactiontype").getValue();

// Define the control for the lookup
var myLookupControl = formContext.getControl("new_party");

if (transactionType === "Sales") {
// Set lookup to show only Accounts
myLookupControl.setEntityTypes(["account"]);
} else if (transactionType === "Service") {
// Set lookup to show only Contacts
myLookupControl.setEntityTypes(["contact"]);
}
}

Have you used any of these methods in your Dynamics 365 projects? Share your experiences or any questions in the comments below. Let’s learn and grow together!

Leave a comment