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
SambitNayakSambitNayak 

Trigger to count the number of related Records(look up - Not Master Detail)

Hi,
I have a Custom Object - Vendor_Contract__c.
Another custon object Work Allocation. It is looking up to object Vendor_Contract (Vendor Contract to Work Allocation is 1 to many relationship). I should not be able to delete a Vendor Contract when there is any related Work Allocation present. 
I dont know where my code is breaking. I am not getting the desired error.

Please have a look into my code and any advice is appreciated

public class LabContractTriggerHandler {
public static void checkWorkAllocation(List<Vendor_Contract__c> LabContractList, boolean isDelete){
    
    Set<Id> listLabCont = New Set<ID>();
    for (Vendor_Contract__c ven: [SELECT ID, (SELECT ID FROM Work_Allocations__r) FROM Vendor_Contract__c WHERE Id IN :LabContractList]){
            if(ven.Work_Allocations__r.size()>0){
                listLabCont.add(ven.Id);
            }
        }
    for(Vendor_Contract__c venCont:LabContractList){
            if(listLabCont.contains(venCont.Id) && isDelete){
                venCont.addError('You cant delete a Labor Contract with Work Allocations. Please delete the Work Allocations before deleting the Labor Contract');
    }
    }

}
}

Best Answer chosen by SambitNayak
SambitNayakSambitNayak
Hey... I used trigger.new instead of old. That was the issue.

All Answers

SambitNayakSambitNayak
I checked the Object settings. It says that : 
What to do if the lookup record is deleted? | Don't allow deletion of the lookup record that's part of a lookup relationship.

I'm getting this error which doesnt make sense:
There's a problem saving this record. You might not have permission to edit it, or it might have been deleted or archived. Contact your administrator for help.
SambitNayakSambitNayak
Hey... I used trigger.new instead of old. That was the issue.
This was selected as the best answer