function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
CodeBeginnerCodeBeginner 

Hi team, can you help me with below code iam new to customization just practing things. Please correct my code

I am trying to write a trigger for acount field update when coresponding contact field in updated. Please help me here the code is not saving 

Trigger FieldupdateOnAccount on Contact(after insert, after update){
set<id> conset = new set<id>();
for(Contact c: trigger.new){
conset.add(c.id);
}
list<Account> Lstacc = [select Name, Phone(select Name, Phone from Contacts) from Account where Contactid in: conset];
List<Account> Acclist = new List<Account>();
if(Lstacc.size()>0 && Trigger.newMap.get(Id).Phone != Trigger.oldMap.get(Id).Phone){
for(Account acc :Lstacc){
for(Contact c: acc.Contacts){

acc.Phone = c.Phone;
Acclist.add(acc);
}
}
Update Acclist;
}
}
Best Answer chosen by CodeBeginner
Soyab HussainSoyab Hussain
Hi CodeBeginner,
You can try this
Trigger FieldupdateOnAccount on Contact(after insert, after update){
    set<id> accountSet = new set<id>();
    for(Contact conRec : trigger.new){
        if(conRec.AccountId != null){
            accountSet.add(conRec.AccountId);  
        }
    }
    Map<Id, Account> accountMap = new Map<Id, Account>([SELECT Phone FROM Account where Id IN :accountSet]);
    if(accountMap.size()>0 ){
        for(Contact con :Trigger.New){
            if(con.AccountId != null && accountMap.containsKey(con.AccountId) ) {
                Account acc = accountMap.get(con.AccountId);
                acc.Phone = con.Phone; 
                accountMap.put(con.AccountId, acc);
            }
        }
    }
    if(accountMap.size() != 0) {
        update accountMap.values();
    }
}
Regards,
Soyab
 

All Answers

Soyab HussainSoyab Hussain
Hi CodeBeginner,
You can try this
Trigger FieldupdateOnAccount on Contact(after insert, after update){
    set<id> accountSet = new set<id>();
    for(Contact conRec : trigger.new){
        if(conRec.AccountId != null){
            accountSet.add(conRec.AccountId);  
        }
    }
    Map<Id, Account> accountMap = new Map<Id, Account>([SELECT Phone FROM Account where Id IN :accountSet]);
    if(accountMap.size()>0 ){
        for(Contact con :Trigger.New){
            if(con.AccountId != null && accountMap.containsKey(con.AccountId) ) {
                Account acc = accountMap.get(con.AccountId);
                acc.Phone = con.Phone; 
                accountMap.put(con.AccountId, acc);
            }
        }
    }
    if(accountMap.size() != 0) {
        update accountMap.values();
    }
}
Regards,
Soyab
 
This was selected as the best answer
CodeBeginnerCodeBeginner
Hi Soyab,

It worked fine, Thanks for the code.