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
Steven Wellman 28Steven Wellman 28 

Not Sure How To Bulkify This

The issue here is that I'm looking at 2 values - phone number and message (text). I need to do a lookup to find the contact that belongs to the phone number and update a field on the contact with the message associated with that phone number. I'm not sure how to do that. I created the trigger and it works this way, but I know it's a bad practice. Can you help me bulkify this:
for(TwilioSF__Message__c msg : Trigger.new){
        if(msg.TwilioSF__Status__c == 'received'){
            List<Contact> cons = [SELECT Id FROM Contact WHERE MobilePhone = :msg.TwilioSF__From_Number_Unformatted__c];
            for(Contact con : cons){
                con.NewTextMessage__c = true;
                con.TxtMsg__c = msg.TwilioSF__Body__c;

                update con;
            }
        }
    }
Any help is much appreciated.
Best Answer chosen by Steven Wellman 28
Raj VakatiRaj Vakati
Here is the code
 
Map<String ,TwilioSF__Message__c> phones = new Map<String ,TwilioSF__Message__c>();


for(TwilioSF__Message__c msg : Trigger.new){
        if(msg.TwilioSF__Status__c == 'received'){
		       phones.put(	msg.TwilioSF__From_Number_Unformatted__c ,msg);
		}
 }
 List<Contact> cons = [SELECT Id FROM Contact WHERE MobilePhone = :phones.keySet()];
 for(Contact con : cons){
                con.NewTextMessage__c = true;
                con.TxtMsg__c = phones.get(con.MobilePhone ).TwilioSF__Body__c;
}
        
		               update con;