-1

i have two objects that contain email fields and i have to compare two objects of records emailids if it matches email address update another field in contact by using of salesforce trigger.

 trigger emailmatchdatacontact on ContactRelationship__c (before insert,before update) 
{
  List<Contact> con= new List<Contact>();
    for(ContactRelationship__c cr:trigger.new)
    {
         Contact c=new Contact(); 
        if(cr.EmailId__c==c.Email)
        {
            cr.Name='divya';
            c.Opt_out_status__c=true;
            cr.ListofContacts__c=c.Id;
            con.add(c);
        }
    }
    update con;
}
  • you need to separately execute a query to retrieve Contact's email and then loop through to match email ids – Santanu Boral Nov 23 '18 at 5:54
-1

Try below code -

trigger emailmatchdatacontact on ContactRelationship__c (before insert,before update) {
    Map<String, Contact> mapOfEmailAndContact = new Map<String, Contact>();
    Set<string> emailSet = new Set<String>();

    for(ContactRelationship__c crVAr : Trigger.New){
      if(crVAr.Email__c != NULL){
        emailSet.add(crVar.Email__c);
      }
    }

    if(!emailSet.isEmpty()){
      for(Contact con : [SELECT ContactField__c, Email__c  FROM Contact WHERE Email__c IN : emailSet]){
          mapOfEmailAndContact.put(con.Email__c, con);
        }

        if(!mapOfEmailAndContact.isEmpty()){
          for(ContactRelationship__c crVAr : Trigger.New){
              if(mapOfEmailAndContact.containsKey(crVar.Email__c)){
                crVar.FieldToUpdate__c = mapOfEmailAndContact.get(crVar.Email__c).FieldOfContact__c;
                //add other field that you want to update on ContactRelation object.
              }
          }
        }

    }       
}
| improve this answer | |
  • Could you add some explanation of what your changes are or what principles are in play here? "Code dump" answers don't help educate the asker or the community by themselves. – David Reed Nov 23 '18 at 12:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.