0

I have product object , contact has lookup relationship,In contact object account has lookup relationship

if we edit the product , the account field should be updated.

I have tried using trigger code:

public static void updaterelatedfield(List<Product2> listNewProduct, Map<Id,Product2> mapOldProduct){
        
        
       
       
        Set<Id> prodId = new Set<Id>();
        for(Product2 prodList : listNewProduct){
           
            prodId.add(prodList.id);
        }
        List<contact> contactList = [Select id,Name from contact where Product__c IN :prodId];
        for(Product2 prod : listNewProduct){
             for(contact con:contactList){
                
                 
                 con.get(account.id).text__c = mapOldProduct.get(prod.id).Sales__c;
                 update con.get(account.id).text__c;
                 
                  
            }
        }
      

It is not updating correctly. How to Bulkify the code ?

1 Answer 1

1

There are few things to improve in your code.
Do you want to update the Accounts on every update of the Product or only when Sales__c is changed? If it is only when the Sales__c is changed, collect the IDs of the product and product in map of id, product Sales field value datatype instead of id set like this:

for(Product2 prodList : listNewProduct){
   if(prodList.Sales__c != mapOldProduct.get(prodList.Id).Sales__c)        
     prodMap.put(prodList.id, prodList.Sales__c);
 }

Next, you should iterate over Contacts where ProductID in the above map keyset and get the Sales value from product to populate on parent account like this:

list<Account> lstAcc = new list<Account>();
for(Contact con : [Select AccountId, Product__c From Contact WHERE Product__c IN :prodMap.keySet()]){
   lstAcc.add(new Account(Id=con.AccountId, text__c=prodMap.get(con.Product__c)));
}

Finally, update the Account List checking the size. Hope this helps!

1
  • it is not working for all the records, only few records only working Commented Feb 18, 2022 at 10:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .