+ 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!!

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?

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){
                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){

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.
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?