In Dynamics 365, we have the ability to filter lookups using addCustomFilter. To do this, we get the control we would like to filter, and add use:
addCustomFilter(filter, entityLogicaName)
Where:
- filter is a FetchXML string
- entityLogicaName is an optional parameter that implies the filter should only work for the entity provided
Let’s say on opportunities all accounts are displayed:
If we would like to filter these accounts to only show the accounts that are based in New York, here’s how we can do it.
First, let’s create the FetchXML. We only need the filter for this to work. Note if you get the error “Invalid Child Node, valid nodes are filter, order, link-entity, attribute, all-attributes, no-attrs” you are providing all the FetchXML and not just the <filter>. Once created, add to the field using addCustomFilter:
function FilterLookup() { var fetchXML = "<filter type=\"and\">" + "<condition value=\"New York\" attribute=\"address1_city\" operator=\"eq\" />" + "</filter>"; Xrm.Page.getControl("parentaccountid").addCustomFilter(fetchXML); }
Next, we will create a new web resource to call on the Opportunity OnLoad:
Now, add addPreSearch() to our lookup control. This method takes a function as a parameter. We will add this function to our OpptyOnLoad and call it:
function AddPreSearchToAccount() { Xrm.Page.getControl("parentaccountid").addPreSearch(FilterLookup); }
Save and Publish.
Now, go to an Opportunity. If you select the account lookup you will see only accounts based in New York:
I AM SPENDING MORE TIME THESE DAYS CREATING YOUTUBE VIDEOS TO HELP PEOPLE LEARN THE MICROSOFT POWER PLATFORM.
IF YOU WOULD LIKE TO SEE HOW I BUILD APPS, OR FIND SOMETHING USEFUL READING MY BLOG, I WOULD REALLY APPRECIATE YOU SUBSCRIBING TO MY YOUTUBE CHANNEL.
THANK YOU, AND LET'S KEEP LEARNING TOGETHER.
CARL
thank you, can we do the same with Email Templates, that filter only the Templates that created by login user
It seems this doesn’t really work in the case when you want to fetch all contacts in the hierarchy for an account. Because the contact field is tightly coupled to account. On Cases.
Have you seen this behaviour? I think it has do do with the lookupstyle andor depedent attribute of the contact field:
Hi,
how can you use this for linked entities (NN Relations)? I want to custom filter based on the NN relation, or else, show all records.
Hi Anas,
Unfortunately these custom JS function do not support complex searching scenarios yet like NN relationship.
Hi Carl, Can we use the variable in query string like name and id as when i use its not working.
formContext.getControl(“product”).addPreSearch(()=>{
var filter=`
`;
formContext.getControl(“product”).addCustomFilter(filter);