0

Here is my apex class:

public class ContactMasterHandler {
    public void CreateContactRelationshipByContact(List<Contact> list_Contacts){
        list<Contact_Relationship__c> conList = new list<Contact_Relationship__c>();
        for(Contact newConts:list_Contacts){
           if(newConts.Contact_Relation__c == true && trigger.oldmap.get(newConts.Id).Contact_Relation__c!=true){
                Contact_Relationship__c cr = new Contact_Relationship__c();
                cr.Name = newConts.LastName + ' ' + newConts.FirstName;
                cr.Contact__c = newConts.id;
                conList.add(cr);
            }
        }
        insert conList;
    }
}

trigger CreateCronContactCreation on Contact (after insert, after update) {
    if(trigger.isAfter){
        if(trigger.isInsert || trigger.isUpdate){
            ContactMasterHandler ConIns = new ContactMasterHandler();
            ConIns.CreateContactRelationshipByContact(trigger.New);
        }
    }
}
1
  • Well, this is your trigger variable which doesn't exist. You have to passe the oldMap to your method as a parameter: public void CreateContactRelationshipByContact(List<Contact> list_Contacts, Map<Id, Contact> oldMap){ Then in your trigger: ConIns.CreateContactRelationshipByContact(trigger.New, Trigger.oldMap); Oct 28, 2019 at 15:58

1 Answer 1

1

I would pass the oldmap as a parameter as well. You're currently only passing the new trigger variable. I'd also look at your logic, you're currently comparing the old value even if the trigger context is insert which wouldn't have any old value. You should consider separating that out (no need to compare old values on after insert).

trigger CreateCronContactCreation on Contact (after insert, after update) {
    if(trigger.isAfter){
        if(trigger.isUpdate){
            ContactMasterHandler ConIns = new ContactMasterHandler();
            ConIns.CreateContactRelationshipByContact(trigger.New,trigger.oldmap);
        }
        if(trigger.isInsert){
          //no need to check old values on insert
        }
    }
}
public class ContactMasterHandler {
    public void CreateContactRelationshipByContact(List<Contact> list_Contacts, Map<Id, Contact> oldMap){
        list<Contact_Relationship__c> conList = new list<Contact_Relationship__c>();
        for(Contact newConts:list_Contacts){
           if(newConts.Contact_Relation__c == true && oldmap.get(newConts.Id).Contact_Relation__c !=true){
                Contact_Relationship__c cr = new Contact_Relationship__c();
                cr.Name = newConts.LastName + ' ' + newConts.FirstName;
                cr.Contact__c = newConts.id;
                conList.add(cr);
            }
        }
        insert conList;
    }
}

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.