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
Akash ShrirameAkash Shrirame 

Find the First 2 Contacts With the Highest Salary and Update the name in a custom field Separated by Comma ( , )



a.Create a new Custom text field on account named "Top Salary Contacts".
b. Create a custom number type field on Contact with 2 decimal places named "Salary" in Contact.
Akash ShrirameAkash Shrirame
trigger HighestSalary on Contact (after insert,after update) {
     Set<id>idSet = new Set<id>();
    for(Contact con : Trigger.new){
        if(con.accountid!=null){
            idset.add(con.accountid);
        }
    }
    
    Map<id,contact>mymap = new map<id,contact>();
    List<Account>acclist = [Select id,Top_Salary_Contacts__c,(Select id,Name,Salary__c from Contacts where Salary__c != null order by Salary__c desc limit 2) 
                            from account where ID IN:idset];
    for(Account acc : acclist){
        mymap.put(acc.id,acc.contacts);
    }
    
    List<Account>alist = new List<Account>();
    for(Account c : acclist){
        
        c.Top_Salary_Contacts__c = mymap.get(c.id).name;
        alist.add(c);
    }
    
    if(alist.size()>0){
    update alist;
    }
}


Error : HighestSalary: execution of AfterUpdate caused by: System.QueryException: List has more than 1 row for assignment to SObject External entry point

How to Avoid this and Assign 2 values in 1 field and Separate that values by comma.
AnkaiahAnkaiah (Salesforce Developers) 
Hi Akash,

try with below code.
trigger HighestSalary on Contact (after insert,after update) {
     Set<id>idSet = new Set<id>();
    for(Contact con : Trigger.new){
        if(con.accountid!=null){
            idset.add(con.accountid);
        }
    }
    Map<id, Set<String>> mapaccidwithcontactnames = new Map<id, Set<String>>();
    Map<id,contact>mymap = new map<id,contact>();
    List<Account>acclist = [Select id,Top_Salary_Contacts__c,(Select id,Name,Salary__c from Contacts where Salary__c != null order by Salary__c desc limit 2) 
                            from account where ID IN:idset];
    for(Account acc : acclist){
	Set<String> contactnames = new Set<String>();
	if(acc.contacts.size()>0){
	for(contact con:acc.contacts){
	contactnames.add(con.Name);
	}
	}
        mapaccidwithcontactnames.put(acc.id,contactnames);
    }
    
    List<Account>alist = new List<Account>();
    for(Account acc : [select id,Top_Salary_Contacts__c from account where id=:mapaccidwithcontactnames.keyset()]){
	
	if(mapaccidwithcontactnames.containskey(acc.id)){
        
        c.Top_Salary_Contacts__c = mapaccidwithcontactnames.get(acc.id);
        alist.add(c);
		}
    }
    
    update alist;

}

If this helps, Please mark it as best answer.

Thanks!!​​​​​​​