1

I am trying to write a trigger where if account has only one associated contact left then prevent deletion.

I wrote a test class to validate the same and found this does not work for mass deletions, if anyone could suggest

trigger triggerContact on Contact(Before Delete) {

    List <Contact> ConDel = new list <Contact>();
    Set <ID> AccID = New Set <ID>();
    Set <ID> AcccID = New Set <ID>();
    List <Contact> ContDel = [Select id, accountid from contact where id in: Trigger.old];
    for (Contact Cont: ContDel) {

        AccID.add(Cont.accountID);
    }


    AggregateResult[] Agg = [Select count(id) total, accountid acid from contact where accountid in: AccID group by accountid];
    For(AggregateResult Result: Agg) {

        if (Result.get('total') == 1) {
            AcccID.add((ID)(Result.get('acid')));

        }
    }



    For(ID Acc1: AcccID) {
        For(Contact Con: Trigger.old) {

            if (Con.accountid == Acc1) {
                Con.adderror('Cannotdelete if only one contact is present');
            }

        }
    }
}

1 Answer 1

2

There is a flaw in your logic, if you delete contacts 1 by 1, then it wont allow you to delete the last contact.

But if you delete all contacts in bulk, it will allow you to do that as in your code Result.get('total')==1 will never be true, as the total will be multiple contacts queried.

You can fix it by the way I mentioned. That being said, You dont need an extra SOQL to get accountID.

 trigger triggerContact on Contact (Before Delete) {

    List<Contact> ConDel = new list<Contact>();
    Set<ID> AccID = New Set<ID>();
    Set<ID> AcccID = New Set<ID>();

    for(Contact Cont :Trigger.old){

       AccID.add(Cont.accountID);
    }


     AggregateResult[] Agg = [Select count(id) total, accountid acid from contact where accountid in :AccID 
                                AND ID not In :Trigger.old group by accountid];

                                System.debug(JSON.serializePretty(Agg ));
        if(Agg.size()>0){
            for(AggregateResult Result:Agg){

                if (Result.get('total')==0){

                    Trigger.oldMap.get(String.valueOf(Result.get('acid '))).addError('Cannotdelete if only one contact is present');
                }
            }
        }
        else{

            Trigger.old[0].addError('Cannotdelete if only one contact is present');
        }

}

1
  • Thanks Pranay, it did help to solve the issue. Thanks again.
    – SKSFDC
    Commented Jul 31, 2018 at 10:57

You must log in to answer this question.

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