+ Start a Discussion

there are some contacts of different types under accounts, i want to autopopulate these contacts of respective type in to the custom fields which are lookup to contact object in the opportunity field section,how can i achieve this with apex code


I think I'd do this with a trigger. Something like this: (Note, this is essentially pseudocode and not intended to compile)
Trigger PopulateCustomContactsOnAccount on Contact (after update, after create) {

  List<Account> accounts = new List<Account>();
  List<Account> accountids = new List<Account>();
  Map<Id, List<Contact>> contactsByAccountId = new Map<Id, List<Contact>>();

  for(Contact c :trigger.new){
    if(contactsByAccountId.containsKey(c.accountId) {
    } else {
      contactsByAccountId.put(c.accountId, new List<Contact>{c});

  accounts = [SELECT id, Field1, Field2 FROM Account where ID in :accountIds];

  for(Account a: accounts){
    for(Contact c:contactsByAccountId.get(a.id){
    if(c.recordtype = 'foobarbaz'){
      a.foobarbaz__c = c.id;
    } else if (c.recordtype = 'barfoo'){
      a.barfoo__c = c.id
    } // etc

  try {
    update accounts;
  } catch (DMLException e){
  // do something with your exception


Thanks Kevin,but my requirement is incomplete with this code i want to autopopulate these contacts in to Opportunity Object in to respective custom fields.
Hi kevin there is similar kind of request as above 
i need apex trigger code to autopopulate the custom fields(lookup to contact) on the new opportunity object from the existing opportunity associated to the same account upon creating the new opportuntiy.