i have handler trigger which calling a apex class, i want that when i am inserting a new contact through UI when i enter email field of new contact then the new contact's phone number must be that of previous contact phone number whose previous contact's Email is same as new contact email.

Example - i have 10 records of contacts in my org, one of them is Gabriel Henly, Phone - 8115122795, email is [email protected]

when i create a new contact named as Zain and email as [email protected], its phone number field should automatically be 8115122795 after saving it

Except - I don't want to use nested for loop

Please help me out with this, I will be very thankfull to you.

1 Answer 1


When you don't want a nested for loop, you want a Map. That involves a three step process I call the Aggregate-Query-Update pattern.

trigger PhoneUpdate on Contact (before insert) {
  // Aggregate
  Map<String, String> emailToPhone = new Map<String, String>();
  for(Contact record: Trigger.new) {
    emailToPhone.put(record.Email, null); // Empty value for now
  // Query
  for(Contact record: [SELECT Email, Phone FROM Contact WHERE Email = :emailToPhone.keySet()]) {
    emailToPhone.put(record.Email, record.Phone);
  // Update
  for(Contact record: Trigger.new) {
    String phone = emailToPhone.get(record.Email);
    if(phone != null) {
      record.Phone = phone;
  • thankyou so much Aug 18, 2021 at 12:14

You must log in to answer this question.

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