Saturday, September 15, 2012

How set Default View for a Lookup field in MS CRM 2011

Step 1: Create two new custom public views on Contact Entity
Step 2: Create a OptionSet field on Account entity name "Contact Types" with two values.
Step 3: Create a new javascript file (FirstJavaScript) with following scripting
function ChangeDefaultLookupViewOnContactTypeChange()
{
var MyValue = Xrm.Page.getAttribute("new_contacttypes").getValue();
if (MyValue == 100000000)
{
 Xrm.Page.getControl("primarycontactid").setDefaultView("XXXXXXXX-XXXX-E111-B30B-080027D26D76");
}
if (MyValue == 100000001)
{
Xrm.Page.getControl("primarycontactid").setDefaultView("XXXXXXXX-F2FE-E111-B30B-080027D26XXX");
}
}

function SetDefaultCustomerLookupOnPageLoad()
{
document.getElementById("customerid").setAttribute("defaulttype", "2"); //2 for contact and 1 for account
Xrm.Page.getControl("customerid").setDefaultView("XXXXXXXX-XXXX-E111-B30B-080027D26D76");
}
Step 4: Customize Opportunity Entity and use "SetDefaultCustomerLookupOnPageLoad" Javascript method on Form OnLoad() method
Step 5: Customize Account Entity and use "ChangeDefaultLookupViewOnContactTypeChange" Javascript method on Contact Types OnChange() method
Note: In case of if you don't know about GUID of Custom Views then use following query on Database:
select SavedQueryId GUID, Name from SavedQueryBase where name in('Custom View 1', 'Custom View 2')