D365: Set Customer field to default to Contact

Here's a handy little JavaScript that lets you set a Customer Field in CRM to default to Contact instead of Account. A Customer Field is a "special type" of field in CRM that can either be set to an Account or Contact. When you add a custom one in CRM, it defaults the lookup to go to Accounts first - the user then has to manually (every time!) change it to Contacts if they want to select a Contact record.

There are some client scenarios where having the default as Contact is better. To do that, use the JavaScript below:

function setRepToContact(executionContext) {
    var formContext = executionContext.getFormContext();
    formContext.getControl("new_representative").setEntityTypes(['contact', 'account']);
    formContext.getControl("new_representative").setDefaultView("{A2D479C5-53E3-4C69-ADDD-802327E67A0D}");
}

and then you can call this function onLoad() for your form in CRM. In the above code, "new_representative" is the name of the customer field. Ensure you use all lower case for 'contact' and 'account' or this script won't work. And just FYI, the Guid A2D479C5-53E3-4C69-ADDD-802327E67A0D is the one for the Contact Lookup View - it is the same in every CRM / Dynamics 365 instance!

For those it might help, here are the steps (this assumes you've already created your custom "Customer" field called new_representative):

  1. In your CRM Solution or under Customizations, create a new Web Resource and call it something useful (ie: SetCustomerDefaultToContact.js).
  2. Set the Type as Script (JScript) and click on "Text Editor" to paste in the above code:
  3. Once done, Publish your changes, and then go edit the Form where this field is displayed.
  4. Under "Form Properties", click the "Add" button to add your new JavaScript library to the Form.
  5. Then under "Event Handlers", choose "Form"... "OnLoad"... and then click Add.
  6. Choose your library in the "Library" drop down.
  7. Enter setRepToContact in the Function field.
  8. Ensure you check "Enabled".
  9. Ensure you check "Pass execution context as first parameter" then click OK.
  10. Here are some screenshots to make it clearer:

Publish all your customizations and try it out!