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
Lara BallwieserLara Ballwieser 

insert contact after insert case

Hello everbody,

i have to write a trigger that insert a case.  if the email in this case is not in a contact object the trigger create a contact. I tried this:

trigger CaseTrigger on Case (after insert) {        
    for(Case ca:trigger.new){      
            
        Contact[] caseWithEmail = [SELECT Id,Email FROM Contact WHERE Email = :ca.SuppliedEmail];
            
        if(caseWithEmail.isEmpty()){
            
        Contact newContact = new Contact(FirstName = ca.First_Name__c, LastName = ca.Last_Name__c, Phone = ca.SuppliedPhone, Email = ca.SuppliedEmail,
                                        MailingStreet = ca.MailingStreet__c, MailingCity = ca.MailingCity__c, MailingPostalCode = ca.MailingPostalCode__c,
                                        MailingState = ca.MailingState__c);
     insert newContact;
  }
    } 
}

I think a piece is absence but I don't know what it is.
Can somebody help me to find it?

Thank you!
Best Answer chosen by Lara Ballwieser
Lara BallwieserLara Ballwieser
Hey everybody,

for everyone how will have had this problem in future. I have found the final solution:
 
Trigger:
trigger CaseTrigger on Case (before insert) {	

    if(trigger.isInsert && trigger.isBefore){
        Helper_CaseTrigger.insertContact(trigger.new);
    }
  }

Helper Class:
public class Helper_CaseTrigger {
    public static void insertContact(List<Case> caseList){
        try{
            Set<String> contactWithEmail = new Set<String>();
            List<Contact> actualContactList = new List<Contact>();
            List<Contact> newContactList = new List<Contact>();
            
            for(Case ca:caseList){
                if(!String.isEmpty(ca.SuppliedEmail)){
                    contactWithEmail.add(ca.SuppliedEmail);
                }
            
            }
            if(contactWithEmail.size() > 0){
                actualContactList = [select id from Contact where Email IN: contactWithEmail];
                
            }

            for(Case ca:caseList){
                if(actualContactList.size() == 0){
                	if(!String.isEmpty(ca.First_Name__c) && !String.isEmpty(ca.Last_Name__c) &&
                       !String.isEmpty(ca.SuppliedEmail) && !String.isEmpty(ca.SuppliedPhone) && 
                       !String.isEmpty(ca.MailingStreet__c) && !String.isEmpty(ca.MailingCity__c) &&
                       !String.isEmpty(ca.MailingPostalCode__c) && !String.isEmpty(ca.MailingState__c)
                       ){
                                     Contact newContact = new Contact();
                           			 
                       				 newContact.FirstName = ca.First_Name__c;
                       				 newContact.LastName = ca.Last_Name__c;
                       				 newContact.Email = ca.SuppliedEmail;
                       				 newContact.Phone = ca.SuppliedPhone;
                       				 newContact.MailingStreet = ca.MailingStreet__c;
                       				 newContact.MailingPostalCode = ca.MailingPostalCode__c;
                       				 newContact.MailingCity = ca.MailingCity__c;
                       				 newContact.MailingCountry = ca.MailingCity__c;
                       				 newContact.MailingState = ca.MailingState__c;
                       			     ca.ContactId = newContact.Id;
                       				 newContactList.add(newContact);
                       				 
                   		}
                	}
                 }
                if(newContactList.size()>0){insert newContactList;}	
            
        }catch(exception e){
            System.debug('Exception in Line:' + e.getLineNumber());
            System.debug('Message for Exception:' + e.getMessage());
        }
    }
}

You also have to require the Web-Email field when you use Web-to-Case!!!

All Answers

Ravi Dutt SharmaRavi Dutt Sharma
I suggest you to read about trigger bulkification. There should not be any SOQL query inside a for loop. Also no DML operations inside the for loop.
Ajay K DubediAjay K Dubedi
Hi Lara,
Try below code:
trigger CaseTrigger on Case (before insert) {
    if((trigger.isInsert && trigger.isBefore)) {
        CaseTrigger_handler.insertContact(trigger.new);
    }
}
Handler:
public class CaseTrigger_handler {
    public static void insertContact(List<Case> caseList) {
        try {
            Set<String> emailSet = new Set<String>();
            List<Contact> conList = new List<Contact>();
            List<Contact> newConList = new List<Contact>();
            for(Case c : caseList) {
                if(!String.isEmpty(c.SuppliedEmail)) {
                    emailSet.add(c.SuppliedEmail);
                }
            }
            if(emailSet.size() > 0) {
                conList = [SELECT Id FROM Contact WHERE Email IN: emailSet LIMIT 10000];
            }
            //If you want to query that contacts whose Email field is same as inserted case field then 
            //you can use above query.
            //And if you want to insert new contact after inserting the case then follow below code
            for(Case c : caseList) {
                if(!String.isEmpty(c.SuppliedEmail) && !String.isEmpty(c.First_Name__c) && !String.isEmpty(c.Last_Name__c) && !String.isEmpty(c.SuppliedPhone)
                   && !String.isEmpty(c.MailingStreet__c) && !String.isEmpty(c.MailingCity__c) && !String.isEmpty(c.MailingPostalCode__c)
                   && !String.isEmpty(c.MailingState__c)
                  ) {
                      Contact con = new Contact();
                      con.FirstName = c.First_Name__c;
                      con.LastName = c.Last_Name__c;
                      con.Phone = c.SuppliedPhone;
                      con.Email = c.SuppliedEmail;
                      con.MailingStreet = c.MailingStreet__c;
                      con.MailingCity = c.MailingCity__c;
                      con.MailingPostalCode = c.MailingPostalCode__c;
                      con.MailingState = c.MailingState__c;
                      newConList.add(con);
                  }
            }
            if(newConList.size() > 0) {
                insert newConList;
            }
            
        } catch (Exception ex) {
            system.debug('Exception---ofLine--->' + ex.getLineNumber());
            system.debug('Exception---Message--->' + ex.getMessage());
        }
    }
}

And Ravi is right, you need to read about trigger bulkification as:
1. Never ever write a SOQL query inside any “for” loop. If you do that, your trigger is guaranteed to hit the governor limits.
2. Never ever perform a DML operation inside a “for” loop.
3. Do not fetch unnecessary data. Only fetch those fields and objects in your SOQL that you really require.
4. Always try to separate trigger and it's handler class.
5. In your code try to put null check conditions at every place where the record has the possibility to come null or undefined.
Follow this link also:
http://www.sfdc99.com/2014/01/18/bulkifying-code/

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks,
Ajay Dubedi
 
Lara BallwieserLara Ballwieser
Hey thank you for your answers. Im sorry, Im a beginner in salesforce programming. 
@Ajay i tried your code but there is already the same problem. But thanks for your help. I will try to solve the problem and if i fixed it, I can write here again.

 
Lara BallwieserLara Ballwieser
Hey again,
@Ajay I wrote a test for your solution and it is working well, but it dont create a contact in my application at all. I dont know whats the problem.
Do you have any idea what it could be?
Lara BallwieserLara Ballwieser
Hey everybody,

for everyone how will have had this problem in future. I have found the final solution:
 
Trigger:
trigger CaseTrigger on Case (before insert) {	

    if(trigger.isInsert && trigger.isBefore){
        Helper_CaseTrigger.insertContact(trigger.new);
    }
  }

Helper Class:
public class Helper_CaseTrigger {
    public static void insertContact(List<Case> caseList){
        try{
            Set<String> contactWithEmail = new Set<String>();
            List<Contact> actualContactList = new List<Contact>();
            List<Contact> newContactList = new List<Contact>();
            
            for(Case ca:caseList){
                if(!String.isEmpty(ca.SuppliedEmail)){
                    contactWithEmail.add(ca.SuppliedEmail);
                }
            
            }
            if(contactWithEmail.size() > 0){
                actualContactList = [select id from Contact where Email IN: contactWithEmail];
                
            }

            for(Case ca:caseList){
                if(actualContactList.size() == 0){
                	if(!String.isEmpty(ca.First_Name__c) && !String.isEmpty(ca.Last_Name__c) &&
                       !String.isEmpty(ca.SuppliedEmail) && !String.isEmpty(ca.SuppliedPhone) && 
                       !String.isEmpty(ca.MailingStreet__c) && !String.isEmpty(ca.MailingCity__c) &&
                       !String.isEmpty(ca.MailingPostalCode__c) && !String.isEmpty(ca.MailingState__c)
                       ){
                                     Contact newContact = new Contact();
                           			 
                       				 newContact.FirstName = ca.First_Name__c;
                       				 newContact.LastName = ca.Last_Name__c;
                       				 newContact.Email = ca.SuppliedEmail;
                       				 newContact.Phone = ca.SuppliedPhone;
                       				 newContact.MailingStreet = ca.MailingStreet__c;
                       				 newContact.MailingPostalCode = ca.MailingPostalCode__c;
                       				 newContact.MailingCity = ca.MailingCity__c;
                       				 newContact.MailingCountry = ca.MailingCity__c;
                       				 newContact.MailingState = ca.MailingState__c;
                       			     ca.ContactId = newContact.Id;
                       				 newContactList.add(newContact);
                       				 
                   		}
                	}
                 }
                if(newContactList.size()>0){insert newContactList;}	
            
        }catch(exception e){
            System.debug('Exception in Line:' + e.getLineNumber());
            System.debug('Message for Exception:' + e.getMessage());
        }
    }
}

You also have to require the Web-Email field when you use Web-to-Case!!!
This was selected as the best answer