I've written in the past about what must be changed (or improved) in Microsoft CRM and one of the things I hate about it is the lookup feature: wonderful to have the ability to create a lookup field with just setting a relation, but why there's not an easy way to create a custom lookup (for example with filters)? It's a basic feature on every "serious" system.
Today, browsing the CRM Sandbox page, I've found this wonderful post: Custom Lookup Dialog for Microsoft Dynamics CRM 3 by Curt Spanburgh. The solution that Curt has given uses fetchXML queries:
// Use additionalparams to manipulate the URL. Since additionalparams append anything to the end of the URL query, you can use 2 lines of code to trick it to do what you want.
/* Filter Lookup for Phase that has the same tractid */
crmForm.all.new_phaseid.lookupbrowse = 1; // This turn on filter
crmForm.all.new_phaseid.additionalparams = "fetchXml=<fetch mapping='logical'><entity name='new_phase'><all-attributes/><filter type='and'><condition attribute='new_tractid' operator='eq' value=' " + crmForm.all.new_tractid.DataValue[0].id+"' /></filter></entity></fetch> ";
There's an interesting post by Ronald Lemmen that explains how to use fecthXML queries: Using Advanced Find for FetchXml.
As Ronald explains, "you can just open the Advanced find page and build the query as you like. Then run the query to see if it returns the data as you wish it should. If you are satisfied with the results and you want to know what query was sent into the CRM Framework, then press F11 to get the address bar and enter this script and press enter.
javascript:alert(resultRender.FetchXml.value);
If you get a warning about leaving the page, just press 'ok' and then the query which is sent to the framework opens up in a popup. Unfortunately you cannot select the text to copy and paste. But with Windows XP and Windows Server 2003 you can copy all text on the popup by clicking somewhere on the popup (not on the button "OK" ofcourse) and pressing ctrl+c. Now in notepad you can paste the text of the FetchXML.".
These two posts makes the trick: set your filter query with Advanced Find in CRM, past the fetchXML text in Notepad and finally replace the additionalparams in the script above with your text just copied. You're ready to use your custom lookup dialog on your CRM code.
Wonderful! 