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
iswarya sekar 7iswarya sekar 7 

Hii!! how to auto populate contact and account name based on email given in case using Triggers!! please help me!!

goabhigogoabhigo
Can you explain little more on use case? Also what should happen if there is no matching Account/Contact found for the specific email ID?

--
Abhi
iswarya sekar 7iswarya sekar 7
public class UpdateContactName {
    
    public static void methodTopopulateContact(List<Case> cs){
        String emailField;
        
        List<Case> updateCases=new List<Case>();
        
        for(Case newCase:cs){
            if(newCase.Profile_received_from_Email__c!=null){
                emailField = newCase.Profile_received_from_Email__c;
                system.debug('The email field is'+emailField);
            }
        }
        
        Contact con=[select accountId,Id,email from Contact where email=:emailField];
        
        if(con!=null && con.accountId!=null){
            
            for(Case cse:cs){
                cse.contactId=con.id;
                cse.accountId=con.accountId;
                updateCases.add(cse);
            }
        }
    }
}

Its working fine in Developer Edition. But it is not working in Sandbox.. What is the problem.. Thanks in Advance.
iswarya sekar 7iswarya sekar 7
Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger caseTrigger caused an unexpected exception, contact your administrator: caseTrigger: execution of BeforeUpdate caused by: System.QueryException: List has no rows for assignment to SObject: Class.UpdateContactName.methodTopopulateContact: line 15, column 1.

when im giving email, its updating contact name, but when the field is empty. it throwing the error as above.
goabhigogoabhigo
Obviously, because the query is not returning any Contact record since it did not find matching one. That's the reason I asked what should be done when there is no matching record found.

For your error, you can have a IF condition to check if the emailField is not null, then perform the query.

Further, I still don't understand what should happen if there are multiple contacts found for the email ID. If you want only one, you can try using the LIMIT in your SOQL query.
iswarya sekar 7iswarya sekar 7
What i have to change in my code? Could you please explain it?
thanks.......