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
Mahesh SMahesh S 

Email-to-Case and update few fields in Case object


Hello Community,

Recently we have implemented the Email2Case and all the necessary steps are done properly, it works as expected.

So new req. is when the Case is created from Email2Case, OOTB will assign the Account and Contact feilds if the email exists in the Org. but we want to update fews fields(editable by users) on Case object based Account info. 

when I implemented it in Before Insert Trigger on Case obj. it does NOT really updates the fields. 

so trying to understand the Flow of creation if records. when the SF receive Email from "abcd123@test.com". will it create EmailMessgase record first or Case record first. 

 

this is in BeforeInsert Case Trigger 
public static void updateCaseAcc(List<Case> caseList){
        
        Map<Id, Id> mapAccIds = new Map<Id, Id>();
        for(case e2case : caseList){
            if(e2case.RecordTypeId == e2case_RT && !mapAccIds.containsKey(e2case.Id)){
                mapAccIds.put(e2case.Id, e2case.ContactId);

        }}
        system.debug('Map2'+mapAccIds); //it shows Null=003Au00000mXXXIX0
        
        Map<Id, Account> AccDetails = new Map<Id, Account>([
            SELECT phone, BillingStateCode 
            FROM Account 
            WHERE Id IN (select AccountId from Contact where Id IN :mapAccIds.values())               
        ]);
        
        for(case updateCase: caseList){
            Account acc = AccDetails.get(updateCase.AccountId);
            if(String.isNotBlank(updateCase.AccountId) ){
                updateCase.state__c = acc.BillingStateCode;
                updateCase.mobile__c =  acc.Phone;

            }
        }
    }
 

anyone's help would highly appreciated and thank you in advance!!
 
AnkaiahAnkaiah (Salesforce Developers) 
Hi Mahesh,

you need to write a trigger on emaimessage object.

try with below code.

Trigger:
trigger exampleTrigger on EmailMessage (after insert) {
    set<Id> caseIds = new set<Id>();
    for(EmailMessage message : trigger.new){
	  if(message.parentId != Null){
	    caseIds.add(message.ParentId);
	   }
     }
	if(caseIds.size()>0) {
	CaseHandler.updateCaseAcc(caseIds);
	}
}

Apex Class:
puplic  class CaseHandler{
		
public static void updateCaseAcc(set<id> caseids){

List<Case> caseList = new List<Case>();

for(Case cs:[Select id,state__c,mobile__c,Account.BillingStateCode,Account.Phone from Case WHERE Id IN:caseids AND AccountId!=Null]){
cs.state__c = cs.Account.BillingStateCode;
cs.mobile__c = cs.Account.Phone;
caseList.add(cs);
}

update caseList;

}
}

If this helps, Please mark  it as best answer.

Thanks!!​​​​​​​