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
Anthony Zirilli 10Anthony Zirilli 10 

Bulkify Code (Too many SOQL queries error)

Hi there, 

I just wrote this simple code to delete line item records when a checkbox "Delete Line Items" is true. The only problem is that the querry goes over the governor limits when doing bulk uploads. How would I rework this so that all Print Copy Line items associated with the Print Copy object are deleted when the "Delete Line Items" checkbox is true (which is located on the Print Copy Object). Thank you in advance. 

Best,
Anthony

trigger DeletePrintCopyLineItem on Print_Copy__c (after update,after delete) {
    List<Id>LstID=new List<ID>();
    for(Print_Copy__c PrintCopy : Trigger.old){
    List<Print_Copy_Line_Item__c> existinglineitems = [Select Id from Print_Copy_Line_Item__c Where Print_Copy__r.Delete_Line_Items__c=True];
    delete existinglineitems;
    }
    }
Best Answer chosen by Anthony Zirilli 10
Vivek DeshmaneVivek Deshmane
Hi Anthony,
Please try below code and let me know.
trigger DeletePrintCopyLineItem on Print_Copy__c (after update,after delete) {
    set<Id>setID=new set<ID>();
    for(Print_Copy__c PrintCopy : Trigger.old)
	{
		setID.add(PrintCopy.id)
    
    }
	if(setId.size()>0)
	{
		List<Print_Copy_Line_Item__c> existinglineitems = [Select Id from Print_Copy_Line_Item__c Where Print_Copy__r.Delete_Line_Items__c=True and Print_Copy__c IN :setId];
		if(existinglineitems !=null && !existinglineitems.isEmpty())
		{
         delete existinglineitems;
		}
	}
    }

Best Regards,
-Vivek

All Answers

ManojjenaManojjena
Hi ,

Try with below  code.
 
trigger DeletePrintCopyLineItem on Print_Copy__c (after update,after delete) {
    Set<Id> idSet=new Set<ID>();
    for(Print_Copy__c PrintCopy : Trigger.old){
	  if(PrintCopy.Delete_Line_Items__c=True){
	    idSet.add(PrintCopy.Id);
	  }
	}
    if(!idSet.isEmpty()){
	  List<Print_Copy_Line_Item__c> listToDelete= [ Select Id from Print_Copy_Line_Item__c Where Print_Copy__c IN :idSet];
       if(listToDelete.size() > 0){
	     delete  listToDelete;
	   }
	}
}
Replace Print_Copy__c with the relationship name from  Print_Copy_Line_Item__c  to Print_Copy__c .

Let me know if it helps
 
Vivek DeshmaneVivek Deshmane
Hi Anthony,
Please try below code and let me know.
trigger DeletePrintCopyLineItem on Print_Copy__c (after update,after delete) {
    set<Id>setID=new set<ID>();
    for(Print_Copy__c PrintCopy : Trigger.old)
	{
		setID.add(PrintCopy.id)
    
    }
	if(setId.size()>0)
	{
		List<Print_Copy_Line_Item__c> existinglineitems = [Select Id from Print_Copy_Line_Item__c Where Print_Copy__r.Delete_Line_Items__c=True and Print_Copy__c IN :setId];
		if(existinglineitems !=null && !existinglineitems.isEmpty())
		{
         delete existinglineitems;
		}
	}
    }

Best Regards,
-Vivek
This was selected as the best answer