Now that version 9.0 has the ability to show custom lookup objects in a supported way, it’s about time we solved this problem using supported code. By the way, the unsupported CRM 2016 code still works fine with v9… for now.
The idea of making this use supported code is pretty simple. First, replace the existing Add Existing command function with a custom function. Have the custom function launch a lookup window where we have control over the filters etc. Take the selected records and associate them with our record using the Web API (unfortunately there’s no nice “Associate” wrapper in the Xrm.WebApi, so it’s the long way for this).
If you can’t copy the code below, you can also get it from the GitHub project I created to keep this code in a central location:
The first function is an example of how to use this. In this example it’s filtering the contact lookup on a custom N:N between account and contact, which only shows contacts associated to the account via the parent customer. The bottom two functions are generic functions that perform the lookup/associate logic, so they don’t need to change.
The primaryEntity and relatedEntity parameters will depend on which side you created the N:N from. Typically the primary will be the one which comes first in the relationship schema name, but if it doesn’t work just switch them around (blame Web API for this).
If we needed to filter N:N’s for other entities, we’d just need to copy this first function and modify it as needed for our other requirements. If we need to filter multiple N:N’s or 1:N’s for the same entity, just add an “else if” on the relationship name check to perform your specific logic.
The code in this blog works the same for both 1:N and N:N, so you can use the same functions for both, and just check the relationship name so you know which is which. Also make sure to use the relationship schema name from the 1:N relationship, not the lookup name.
Change the command to use your custom function and library, and then tweak the parameters to pass in the required CRM values. In my case I just needed to add the FirstPrimaryItemId. Also remember to update all the Mscrm display rules/enable rules to “Un-customised = True”.
Publish, and that’s it. The rest should just work. I also added a custom notification indicator to show the associate progress, since Web API does the associates asynchronously, if there’s a lot of records being associated it can take a while to complete, so the notification makes the user experience a bit nicer.