You need to sign in to do that
Don't have an account?
pooja biswas
prevent parent record deletion
Hi
I have the code working for preventing parent record deletion if related child record exists.
what I want to know is if a List object is present inside a loop will it hit governor limits?
Thanks
pooja
I have the code working for preventing parent record deletion if related child record exists.
what I want to know is if a List object is present inside a loop will it hit governor limits?
public class preventaccountdeletion { public void prevent_account_delete(list<Account> acc) { for(Account a:acc) { List<Contact> con=[select AccountID from Contact where AccountID=:a.ID]; List<Opportunity> op=[select AccountID from Opportunity where AccountID=:a.ID]; if ((con.size() > 0) || (op.size() > 0)) a.addError('Cannot Delete Account Because It Has Related Contacts And Opportunities'); } } } trigger trg_preventaccountdelete on Account (before delete) { if (trigger.isDelete) { preventaccountdeletion p=new preventaccountdeletion(); p.prevent_account_delete(Trigger.old); } }
Thanks
pooja
{
Map<Id, Account> mapAccount = new Map<Id, Account>([SELECT Id, (SELECT Id FROM Contacts LIMIT 1) FROM Account WHERE Id IN: acc]);
for(Account objAccount : acc)
{
if(mapAccount.containsKey(objAccount.Id) && mapAccount.get(objAccount.Id).Contacts.isEmpty()) continue;
objAccount.adderror('Cannot Delete Account Because It Has Related Contacts');
}
}
All Answers
I have attached another code, pls let me know if it will also hit governor limits.
if it does, then pls let me know best possible way to avoid it. thanks
pooja
This will not hit the any governor limits but the code is not optimize and not followed the best practices
Thanks,
OK, the code shown in my first post will hit governor limits.
OK, pls tell me how I can optimize the code shown in my latest post?
I require urgent help...
I tried ur code , its fine but cud u pls let me know how to optimize my code?
pooja Biswas
{
Map<Id, Account> mapAccount = new Map<Id, Account>([SELECT Id, (SELECT Id FROM Contacts LIMIT 1) FROM Account WHERE Id IN: acc]);
for(Account objAccount : acc)
{
if(mapAccount.containsKey(objAccount.Id) && mapAccount.get(objAccount.Id).Contacts.isEmpty()) continue;
objAccount.adderror('Cannot Delete Account Because It Has Related Contacts');
}
}
sorry, I didn't understand things
a) why is "LIMIT" clause reqd in SOQL query(1 account can have multiple contacts)
b) I debugged this statement : mapAccount.get(objAccount.Id).Contacts, it returns the contact ID for that particular account
Here we need to check weather we have child record or not.. so we put limit 1
mapAccount.get(objAccount.Id).Contacts will returns the contact id only as we are querying single record of contact correspoding to Account.
This resolves my query.