+ Start a Discussion
harshal patil 007harshal patil 007 

Hello, i want to create trigger for whenever new case create and match that case email filed with account master object records custome email filed if both of email match then assign to the case in related case list of that account how to do that

Best Answer chosen by harshal patil 007
Khan AnasKhan Anas (Salesforce Developers) 
Hi Harshal,

Greetings to you!

Below is the sample code which I have tested in my org and it is working fine. Kindly modify the code as per your requirement.
trigger AssignAccToCase on Case (before insert) {
    
    Map<String, Id> emails = new Map<String, Id>();
    
    for(Case cs : Trigger.new) {
        emails.put(cs.Email__c, cs.Id);
    }
    
    for(Account acc : [SELECT Id, Email__c FROM Account WHERE Email__c IN :emails.keySet()]) {
        emails.put(acc.Email__c, acc.Id);
    }
    
    for(Case cases : Trigger.new) {
        if(cases.Email__c != null && emails.get(cases.Email__c) != null) {
            cases.AccountId = emails.get(cases.Email__C);
        }
    }
}

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas

All Answers

Khan AnasKhan Anas (Salesforce Developers) 
Hi Harshal,

Greetings to you!

Below is the sample code which I have tested in my org and it is working fine. Kindly modify the code as per your requirement.
trigger AssignAccToCase on Case (before insert) {
    
    Map<String, Id> emails = new Map<String, Id>();
    
    for(Case cs : Trigger.new) {
        emails.put(cs.Email__c, cs.Id);
    }
    
    for(Account acc : [SELECT Id, Email__c FROM Account WHERE Email__c IN :emails.keySet()]) {
        emails.put(acc.Email__c, acc.Id);
    }
    
    for(Case cases : Trigger.new) {
        if(cases.Email__c != null && emails.get(cases.Email__c) != null) {
            cases.AccountId = emails.get(cases.Email__C);
        }
    }
}

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
This was selected as the best answer
harshal patil 007harshal patil 007
Awesome.
Thank you so much :)