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
kumar 197kumar 197 

Trigger to Avoid deleting Flights if there are at least 5 associated Bookings

AbhinavAbhinav (Salesforce Developers) 
CHeckn this for reference:

https://salesforce.stackexchange.com/questions/191757/trigger-to-prevent-deletion-of-account-if-account-has-atleast-one-contact-associ

You can have similar solution  changing Api name and >5 for your scenario
 
trigger AccountContactCheck on Account (before delete) { for (AggregateResult ar : [SELECT accountid, count(id)size FROM contact where accountid in : Trigger.oldMap.keySet() GROUP BY accountid]) if(((integer)ar.get('size'))>0) trigger.oldMap.get((id)ar.get('accountid')).adderror('******* Contact is associated with it.you cant delete account'); }

Thanks!
Suraj Tripathi 47Suraj Tripathi 47
Hi Ashutosh,
please use below approach
 
trigger flightTrigger on flight__c (before delete){
    
    if(trigger.isbefore && trigger.isdelete){
        flightHelper.stopDeletionOfFlight(trigger.new);
    }
   
}


public class flightHelper{
 public static void stopDeletionOfFlight(list<flight__c>  list1){
        try{
		list<flight__c> flightList = [select id,(select id from bookings__c) from flight__c where id In:list1];
		map<id,list<booking__c>> IdOfFlightToBookingMap = new map<id,list<booking__c>>();
		
		for(flight__c flObj:flightList){
		IdOfFlightToBookingMap.put(flObj.id,flObj.bookings__c);
		}
		
		for(flight__c flObj:list1){
		if(IdOfFlightToBookingMap.Containskey(flObj.id) && IdOfFlightToBookingMap.get(flObj.id).size()>4){
		flObj.addError('Can't delete this flight');
		}
		}
		
}
catch(Exception e){
        system.debug('Error Message ==>'+e.getMessage() + ' in line number ' + e.getLineNumber());
    }
    
}
}

If you find your Solution then mark this as the best answer.

Thank you!
Regards,
Suraj Tripathi