+ Start a Discussion
Jan Kopejtko 2Jan Kopejtko 2 

Bulkyfing a trigger - please help

Hello, I don't know how to bulkify this. Please help
 
trigger QuoteLineItemEmailBeforeDelete on QuoteLineItem (after delete) {
    Set<Id> quids = new Set<Id>();

    for(QuoteLineItem qli :Trigger.Old) {
        quids.add(qli.QuoteId);
    }

    Quote[] quo = [Select Id, Name, Status, RecordTypeId from Quote Where id In :quids];

    if((quo[0].Status == '2. Validated - Waiting for order' || quo[0].Status == '3. Offer partially entered in SAP' || quo[0].Status == '4. Offer fully entered in SAP')&& (Quo[0].Name.Contains('H3'))) {
  Messaging.reserveSingleEmailCapacity(trigger.size);
    List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
    for (QuoteLineItem qli : Trigger.old) {
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        email.setToAddresses(new String[] {'becommingaprogrammer@example.com'});
        email.setSubject('Oznámení o změně nabídky');
        email.setPlainTextBody('Došlo ke změně nabídky ' + Quo[0].Name + '.\n\n' + 'Pro otevření záznamu v Salesforce klikněte na následující odkaz:\n\n' +  'https://sg--testing.lightning.force.com/lightning/r/Quote/' + quo[0].Id + '/view');
        emails.add(email);
    }

    Messaging.sendEmail(emails);
        
    }
}

 
Anthony McDougaldAnthony McDougald
Hello Jan,
Hope that your day is off to an amazing start. Below is the code that we bulkified for your use case. If you have any questions or need assistance, please feel free to reach out. May God bless you abundantly and have a blessed day.
trigger QuoteLineItemEmailBeforeDelete on QuoteLineItem (after delete) {
    Set<Id> quids = new Set<Id>();
	Integer counter = 0;
	List<Quote> emailList = new List<Quote>();
	List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();

    for(QuoteLineItem qli :Trigger.Old) {
        quids.add(qli.QuoteId);
    }

    Quote[] quo = [Select Id, Name, Status, RecordTypeId from Quote Where id In :quids];
	
	for(Quote q : quo){
		if( (q.Status == '2. Validated - Waiting for order' || q.Status == '3. Offer partially entered in SAP' || q.Status == '4. Offer fully entered in SAP') && (q.Name.Contains('H3')) ){
			counter += 1;
			emailList.add(q);
		}
	}
	
	Messaging.reserveSingleEmailCapacity(counter);

    for (Quote q : emailList) {
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        email.setToAddresses(new String[] {'becommingaprogrammer@example.com'});
        email.setSubject('Oznámení o změně nabídky');
        email.setPlainTextBody('Došlo ke změně nabídky ' + q.Name + '.\n\n' + 'Pro otevření záznamu v Salesforce klikněte na následující odkaz:\n\n' +  'https://sg--testing.lightning.force.com/lightning/r/Quote/' + q.Id + '/view');
        emails.add(email);
    }

    Messaging.sendEmail(emails);
        
}


Best Regards,
Anthony McDougald