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
SavithaSavitha 

Help in FIND functionality in Apex Trigger

Hi All,

An Email to Case is Created. The email sender address is having the Address like '0234155555_fax@cws-boco.com', the system should find the contacts having the Phone or Fax number as '+49 234155555', that contact and its account should be associated with the Created case.

Right now contact is assigning properly. but at one point when 2 contacts are having same phone number and fax number, then I want the case to be associated with only the Fax matching Contact.

Here is my code:
trigger caseContactAccount on Case (before insert, before update) {

 
    list<string> sendaddr1=new list<string>();
    list<Contact> contactList=new list<Contact>();
    list<EmailMessage> em=new list<EmailMessage>();
 
    for(case c:Trigger.new){         
        //if(c.Origin=='Fax'){
           em=[Select Id, FromAddress, ParentId from EmailMessage where ParentId = : c.id];      
       // }
    if(!em.isempty()){
        for(EmailMessage i: em){
        Boolean isMatched = Pattern.matches('[0][0-9]+_fax@cws-boco.com', em[0].FromAddress);          
        system.debug('formattttt checccck'  +isMatched);
      
        if(isMatched){
             
                string code=em[0].FromAddress;
                system.debug('code entering' + code);
                Integer startIndex = code.indexOf('0')+1;
                Integer endIndex = code.indexOf('_');
                sendaddr1.add(code.substring(startIndex,endIndex));             
                code='+49'+sendaddr1[0];
                system.debug('++++++++++++ code ++++++++++---' +code);
              
                try{
                List<List<SObject >>searchList = [FIND :code RETURNING Contact(Id,Name,MobilePhone,Fax,Email)];
                contactList = ((List<Contact>)searchList[0]);              
                Id Conid=contactList[0].Id;
                system.debug('+++++Contact Id++++++' + Conid);
                if(conid!= null){                    
                c.Contactid=Conid;
                update c;
                }else {}
                }
              
                catch(Exception e) {
                        system.debug('Exception Occurred : ');
                }
        }else {}
       }
    }else {}
  
  }
}


Please help me this piece of code.

Kindly help

  
magicforce9magicforce9
Hi Savitha,

I highly suggest we re-write the trigger as I see that this trigger is not bulkified and you'll easily hit the governor limit if multiple cases gets created at one time.

I've tried my best to re-factor it for you...(it might not be prefect but let me know if it works or doesn't)
trigger caseContactAccount on Case (after insert) {

    list<string> sendaddr1 = new list<string>();
    list<Contact> contactList = new list<Contact>();
    List<String> phoneNumbersList = new List<String>();
    Map<String, List<id>> phoneToCaseMap = new <String, List<id>>();
    List<EmailMessage> emailList = new List<EmailMessage>();
    Set<id> caseIds = new Set<id>();
    List<Case> casesToBeUpdated = new List<Case>();
    for(case c:Trigger.new){         
        caseIds.add(c.id);
    
    emailList = [Select Id, FromAddress, ParentId from EmailMessage where ParentId IN :caseIds];

    for(EmailMessage email : emailList){
        Boolean isMatched = Pattern.matches('[0][0-9]+_fax@cws-boco.com', email.FromAddress);          
        system.debug('formattttt checccck'  +isMatched);
  
        if(isMatched){
         
            string code=email.FromAddress;
            system.debug('code entering' + code);
            Integer startIndex = code.indexOf('0')+1;
            Integer endIndex = code.indexOf('_');
            sendaddr1.add(code.substring(startIndex,endIndex));             
            code='+49'+sendaddr1[0];
            system.debug('++++++++++++ code ++++++++++---' +code);
            phoneNumbersList.add(code);

            //This is - if you receive multiple emails from the same sender and those cases gets processed in the same trigger
            if(phoneToCaseMap.ContainsKey(code))
                phoneToCaseMap.get(code).add(email.ParentId);
            else
                phoneToCaseMap.put(code, new List<id>(email.ParentId));

        }
    }
    
    String phoneNumbers = String.join(phoneNumbersList, ' OR ')
    List<List<Contact>> searchList = [FIND :phoneNumbers IN PHONE FIELDS RETURNING Contact(Id,Name,MobilePhone,Fax,Email)];

    //Check if search resulted any records or not
    if(searchList.size() > 0 && searchList.get(0).size() > 0) {

        //Now each rotation of this outer loop is dealing with a specific number, and we can see if the number was found in Mobile or Fax
        //and if its found in both of them then we'll select the contact that has the matching fax number
        for(List<Contact> contacts : searchList){
            //This is straight forward - which means it found one contact for one number
            Case case;
            if(contacts.size() = 1){
                String mobile = contacts[0].MobilePhone;
                for(Id caseId : phoneToCaseMap.get(mobile)){
                        case = trigger.newMap.get(caseId);
                        case.ContactId = contacts[0].id;
                        
                     }
            }
            //This is where it could have found more than one contact and we need to see if the fax number matches for any of those
            else if(contacts.size() > 1) {
               for(Contact con : contacts){
                    if(con.Fax != null && phoneToCaseMap.ContainsKey(con.Fax)){
                        for(Id caseId : phoneToCaseMap.get(con.Fax)){
                            Case case = trigger.newMap.get(caseId);
                            case.ContactId = con.id;
                        }
                        break;
                    }
                    else{
                        for(Id caseId : phoneToCaseMap.get(con.MobilePhone)){
                            Case case = trigger.newMap.get(caseId);
                            case.ContactId = con.id;
                        }
                    }
                }
                if(case != null) casesToBeUpdated.add(case);
            }
        }
    }
    if(!casesToBeUpdated.isEmpty()) update casesToBeUpdated;
}

SavithaSavitha
Thanks for the Reply magic,

But I'm getting an Error Compile Error: Invalid initial value type Id for LIST<Id> at line 34 column 42