You need to sign in to do that
Don't have an account?
Jonas Júnior
I need help with Map<Key,Value> use
Hey guys,
I need help with the code below. It work, but when the second for is running I`m afraid that it cause a system error because it's runing many times the same consult. What I need to do is change this to use a Map<key,value> and stay with only one for and a Map<key,value>. How I do this?
Junior, Jonas C.
I need help with the code below. It work, but when the second for is running I`m afraid that it cause a system error because it's runing many times the same consult. What I need to do is change this to use a Map<key,value> and stay with only one for and a Map<key,value>. How I do this?
public static void stopAccountDelete (List<Account> listAcc){ try{ for(Account acc : listAcc){ for(Opportunity opp : [SELECT AccountId FROM Opportunity WHERE IsWon = true]){ if(acc.Id == opp.AccountId){ acc.Id.adderror('Account cannot be deleted, because exists a Opportunity associated!'); } } } } catch (DmlException e) { System.debug('DML error: ' + e.getMessage()); } catch (Exception ex) { System.debug('System error: ' + ex.getMessage()); } }Thanks,
Junior, Jonas C.
Please try this below code, It's more optimised...
public static void stopAccountDelete (List<Account> listAcc){
Map<id, Account> mapAcctsWithOpps = new Map<id, Account>([SELECT Id,(SELECT AccountId, IsWon FROM Opportunities WHERE IsWon = true) FROM Account WHERE ID IN: listAcc]);
try{
for(Account acc : listAcc){
if(mapAcctsWithOpps.get(acc.id).Opportunities.size() > 0){
acc.adderror('Account cannot be deleted, because exists a Opportunity associated!');
}
}
}
catch (DmlException e) {
System.debug('DML error: ' + e.getMessage());
}
catch (Exception ex) {
System.debug('System error: ' + ex.getMessage());
}
}
All Answers
You can even use trigger.oldMap if you are calling this code from the trigger
I did some adjusts in your code and it worked! Thanks for your help! The new code looks like this: Thanks,
Junior, Jonas C.
Please try this below code, It's more optimised...
public static void stopAccountDelete (List<Account> listAcc){
Map<id, Account> mapAcctsWithOpps = new Map<id, Account>([SELECT Id,(SELECT AccountId, IsWon FROM Opportunities WHERE IsWon = true) FROM Account WHERE ID IN: listAcc]);
try{
for(Account acc : listAcc){
if(mapAcctsWithOpps.get(acc.id).Opportunities.size() > 0){
acc.adderror('Account cannot be deleted, because exists a Opportunity associated!');
}
}
}
catch (DmlException e) {
System.debug('DML error: ' + e.getMessage());
}
catch (Exception ex) {
System.debug('System error: ' + ex.getMessage());
}
}
It got better this way. Thanks for your help!
Thanks,
Junior, Jonas C.