This quick snippet comes in handy every now and then, and now it’s also tested for Dynamics CRM 2013.

Scenario:

I have a bunch of organizations, and a set of Organization Types. Let’s say, we have various client types, with various SLA’s.

In the Case entity, I want to show only the Organizations of specific type(s), that I can support through Cases.

Solution:

First off, create a new web resource if one is not already created for the Case entity.

Then, from the form load event, call this function which uses addPreSearch.

function preFilterLookupOrganization() {   
    Xrm.Page.getControl("control_name").addPreSearch(function () {
        addLookupFilter();
   });
}

This is from the SDK:

addPreSearch

Use this method to apply changes to lookups based on values current just as the user is about to view results for the lookup.

JavaScript 
Xrm.Page.getControl(arg).addPreSearch(handler)

Arguments
Type: Function to add.
Remarks
This method is only available for Updated Entities.

The argument is a function that will be run just before the search to provide results for a lookup occurs. You can use this handler to call one of the other lookup control functions and improve the results to be displayed in the lookup.

 

Next let’s build the handler. We’re building the filter query and add the filter to our control as such:

function addLookupFilter() {
    var myControl = Xrm.Page.getAttribute("control_name").getValue();

    if (myControl != null) {
        fetchXml = "<filter type=’and’><condition attribute=’customertypecode’ value=’1′ operator=’eq’/></filter>";
        Xrm.Page.getControl("control_name").addCustomFilter(fetchXml);
    }
}

Now, it’s all in the filter, and the current example only looks for one specific Organization type. You can build that fetchXml filter as complex as needed, either by pulling if from an advanced find, creating it by hand, or using a 3rd party tool.

Enjoy!

Advertisements