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 

Need help with bulkification

Not sure how to bulkify this trigger:
trigger OppPaymentCollected on Account (after update) {

	List<Opportunity> oppsToUpdate = new List<Opportunity>();

	for (Account acc : Trigger.new) {

		// Get trigger.old and trigger.new versions of the record
		Account oldAcc = Trigger.oldMap.get(acc.Id);
		Account newAcc = Trigger.newMap.get(acc.Id);

		// Create variable to store value to see if payment date has changed.
		Boolean newPayment = oldAcc.Most_Recent_Payment__c != newAcc.Most_Recent_Payment__c;

		// Query and find all Oppos that are 'Sold'
		if(newPayment) {
			List<Opportunity> opps = [SELECT Id, Date_Customer_Paid__c FROM Opportunity WHERE StageName = 'Sold' 
																						  AND Date_Customer_Paid__c = null 
																						  AND AccountId = :acc.Id];

			for (Opportunity oppty : opps) {
				oppty.Date_Customer_Paid__c = Date.Today();
				oppsToUpdate.add(oppty);
			}
		}
	}

	update oppsToUpdate;
}
Any help appreciated.
Best Answer chosen by Steven Wellman 28
Raj VakatiRaj Vakati
Use this code
 
trigger OppPaymentCollected on Account (after update) {

	List<Opportunity> oppsToUpdate = new List<Opportunity>();
Set<Id> accsId = new Set<Id>();
	for (Account acc : Trigger.new) {
		// Get trigger.old and trigger.new versions of the record
		Account oldAcc = Trigger.oldMap.get(acc.Id);
		Account newAcc = Trigger.newMap.get(acc.Id);
		// Create variable to store value to see if payment date has changed.
		Boolean newPayment = oldAcc.Most_Recent_Payment__c != newAcc.Most_Recent_Payment__c;
		// Query and find all Oppos that are 'Sold'
		if(newPayment) {
			accsId.add(acc.Id);
			
		}
	}
	
	List<Opportunity> opps = [SELECT Id, Date_Customer_Paid__c FROM Opportunity WHERE StageName = 'Sold' 
																						  AND Date_Customer_Paid__c = null 
																						  AND AccountId IN :accsId];

			for (Opportunity oppty : opps) {
				oppty.Date_Customer_Paid__c = System.Today();
				oppsToUpdate.add(oppty);
			}
			if(oppsToUpdate.size()>0){

	update oppsToUpdate;
			}
}