2

I have two objects Parent__c and Child__c. Is it possible to somehow restrict deletion of the parent if a child is attached to it?

Tia.

3 Answers 3

1

you can try the below code by replacing the objects and fields API names to correct one

trigger preventDeletion on Parent__c(before delete){
    Set<Id> parentWithChildIds = new Set<Id>();
    Set<Id> parentIds = new Set<Id>();
    for(Parent__c pa : Trigger.Old){
        parentIds.add(pa.Id);
    }
    for(Child__c Ch = [select id, parent__c, parent__r.Id from child where parent__c =: parentIds]){
        parentWithChildIds.add(Ch.parent__r.Id);
    }
    for(Parent__c pa : Trigger.Old){
        if(parentWithChildIds.contains(pa.Id)){
            pa.adderror('This guy has Children, You cannot hurt him!');
        }
    }
}

Basically what we did is just fetched the parents with Children and checked across the parent that we intent to delete.

2
  • n.b. if child is a detail in master detail, a RSF that counts the children would yield without querying whether children exist; also, instead of querying all children with parentId = parents in trigger; query all parents with relationship query including children and test for size of child relationship > 0 - you elim the first for loop and second for loop is replaced with map initialization
    – cropredy
    Commented Jan 6, 2015 at 20:43
  • thoughtful!! 2nd suggestion can eliminate a loop. Little more optimization. Commented Jan 7, 2015 at 4:05
0

Implement a trigger on Parent__c before delete, query child records and add error if Child record exists

0
-3

You can achieve this using trigger.

Try the following trigger example,

trigger ParentTrigger on Parent__c (before delete) {

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

    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...

0

You must log in to answer this question.

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