2

Below is my code but dont know how to validate it exactly in code.new to code

trigger AccountContactCheck on Account (before delete) {
Set<id> accountids=new set<id>();
for(account acc:trigger.old){
    accountids.add(acc.id);
}Map<id,contact>conmap=new map<id,contact>([select accountid from contact where accountid in :accountids]);
System.debug('conmap>>>>'+conmap.keySet());
for(account acc:trigger.old){
    if(conmap.get(acc.id)!=null){
        System.debug('Inside If of account >>>>>>');
        acc.adderror('Contact is associated with it.you cant delete account');

    }
}
2
  • Hey Aditi, are you wondering whether this code will work? I'm curious what you mean by validate other than trying to delete a Contact from an Account.
    – McD
    Commented Sep 12, 2017 at 4:42
  • Yes if account is having any contact then i need to prevent account from deletion.Please help
    – Aditi
    Commented Sep 12, 2017 at 4:47

1 Answer 1

0

You have did mistake while capture conmap Map, In conmap your storing key id as contact id and value as accountid.

if(conmap.get(acc.id)!=null)

In the above code your match account id with contact id , ie.. the reason if condition always be false in your case, your not able go inside if condition.

Try below code it will work for you.

You can use group by clause make shorten in code

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');         
}

OR

Alternate

 trigger AccountContactCheck on Account (before delete) { 
        List<contact> Contacts = [select accountid from contact where accountid in : Trigger.oldMap.keySet()];
        set<id> accIds=new set<id>();
          for(contact con: Contacts)
                 accIds.add(con.accountid);

        for(account acc:trigger.old)
            if(accIds.contains(acc.id))
                acc.adderror('******* Contact is associated with it.you cant delete account');            
    }
7
  • Nitesh.if you have some sample example of trigger with scenarios .can you please provide me.as i am new to sfdc and want to learn triggers
    – Aditi
    Commented Sep 12, 2017 at 5:23
  • Your welcome......
    – NITHESH K
    Commented Sep 12, 2017 at 5:27
  • @Aditi What exactly you wanted ?
    – NITHESH K
    Commented Sep 12, 2017 at 5:28
  • I know the basic .but i am getting stuck when some complex kind of logic i need to build.so i need some scenarios with the triggers where i can actually get the understanding how to build logic .I need some Examples like above which i done.my email Id [email protected]
    – Aditi
    Commented Sep 12, 2017 at 5:37

You must log in to answer this question.

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