top of page

T#1: Set Account dynamically upon choosing the Contact Lookup Field

Updated: Jan 22, 2019

FOUR steps in order to Dynamically SET the Account field after fetching the Contact's parent field:

  1. Copy Paste the four functions

  2. Rename few text to fit into your CRM fields

  3. Save and publish

  4. Add your Javascript OnChange of the Contact field


1. Copy paste the following four functions:

function getAccountRelatedToContact(fieldName)


var contact = Xrm.Page.getAttribute(fieldName);

if (contact === null || contact.getValue() === null)

{ return; }

var contactValue = contact.getValue();

var contactId = contactValue[0].id;

Xrm.WebApi.retrieveRecord("contact", contactId, "? $select=fullname&$expand=parentcustomerid_account($select=name, accountid)").then(

function success(result)


//No parent Account for the contact: clear the form's account field

if(result.parentcustomerid_account == null)




var recordId = result.parentcustomerid_account.accountid;

var recordName =;

// Get the result



function (error) { console.log(error.message);



function GetResult(account)


var recordId = account.parentcustomerid_account.accountid;

var recordName =;

setLookupValue("new_accountid", "account", recordId, recordName);


function setLookupValue(lookupSchemaName, entitySchemaName, recordId, recordName)



[ { entityType: entitySchemaName, id: recordId, name: recordName}]);


2. Find and Replace the following text to fit in your CRM context

Replace "new_accountid" by "your CRM field name between quotation mark"

Replace parentcustomerid_account by AccountFieldNamePresentOnContact'sForm

3. Save your Javascript and publish

After having renamed the corresponding sections of the code, Save and Publish your Javascript.

4. Add your Javascript OnChange of the Contact field

a/ Go to the Custom Entity form that your code will trigger at and Click on Form Properties.

b/ On the Events Tab, pick up your Javascript and call the function:

and pass to it the parameter: "new_contactid"

NB: "new_contactid" stands for the name of the contact field present on the custom entity's form

146 views0 comments

Recent Posts

See All
bottom of page