0

I started writing the following trigger: Basically what I am trying to achieve is to prevent deletion of Parent__c if it has a Child__c attached.

    trigger ParentTrigger on Parent__c (before delete) {

    //get all the child objects
    List<Child__c> childList = new List<Child__c> ([SELECT id, Parent__c FROM Child__c]);

   //run through all the parents --> here I need to somehow say that the trigger should apply only to   parents that have children attached    
for (Parent__c par : Trigger.Old) {
        if (childList.size() > 0) {
            par.adderror('Cannot be deleted');
        }
      }
    }

Tia.

0

3 Answers 3

5

I suggest you make a map of Children by Parent Id rather than a list, so you can check per Parent whether he has a Child. By using a map, you can also show which Children are blocking the deletion. Also, it's a good idea to only retrieve the Parent-records that are actually being deleted using a list and "IN :parentIds".

Example:

trigger ParentTrigger on Parent__c (before delete) {
    List<Id> parentIds = new List<Id>();
    for(Parent__c p : Trigger.Old)
        parentIds.add(p.Id);

    Map<Id, List<Child__c>> childMap = new Map<Id, List<Child__c>>();
    for (Child__c child : [SELECT id, Parent__c FROM Child__c WHERE Parent__c IN :parentIds]) {
        if(!childMap.containsKey(child.Parent__c))
            childMap.put(child.Parent__c, new List<Child__c>());
        childMap.get(child.Parent__c).add(child);
    }

    for (Parent__c par : Trigger.Old) {
        if (childMap.containsKey(child.Parent__c)) {
            par.adderror('Cannot be deleted');
        }
    }
}

Keep in mind that I typed the code in a textbox, tell me if it doesn't work.

0
Map<Id,Parent__c> parMap = new Map<Id,Parent__c>([SELECT Id,(SELECT Id from Child__r) from Parent__c WHERE ID IN: oldMap.keyset()]);
    for(Parent__c parent : oldList){
        if(parMap.containskey(parent.Id)){
            if(parMap.get(parent.Id).Child__r.size() > 0){
                parent.addError('Parent can not be deleted as its having child records' );
            }
        }
    }
-1

You can achieve this using trigger.

Try the following trigger example,

trigger ParentTrigger on Parent__c (before delete) {

Set pCIds = new Set();

Set<Id> pIds = new Set<Id>();

for(Parent__c p : Trigger.Old){

    pIds.add(p.Id);

}

for(Child__c C : [select id, parent__c, parent__r.Id from Child__c where parent__c =: pIds])

    {

    pCIds.add(C.parent__r.Id);

}

for(Parent__c objParent : Trigger.Old){

    if(pCIds.contains(objParent.Id)){

        objParent.adderror('OMG CHILD HAI RE USKE MAT KAR DELETE');

    }

}
}

The above trigger will execute while you try to delete a record that has a child records exist.

Hope this will help you...!

don't forget to mark best answer...

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .