You need to sign in to do that
Don't have an account?
noobfn
Apex Trigger to Populate Account Owner Email when Account is created
I pretty new to apex, and I needed to do this trigger using map collection. So I started and I'm stuck. Where do i go from here? When I create a new account the trigger should populate the account owner's email. Thank you.
trigger insertEmailMap on Account (before insert, before update) {
Map<Id, String> emailMap = new Map<Id, String>();
List<User> ownerEmail = [select id, email FROM User WHERE id IN: emailMap.Keyset()];
for(user u: ownerEmail){
emailMap.put(u.id, 'email');
system.debug(emailMap);
}
system.debug('map ' + emailMap);
Hi,
trigger insertEmailMap on Account (before insert, before update) {
Map<Id,Id> mapOwnerEmail = new Map<Id,Id>();
for (Account acc : Trigger.new){
mapOwnerEmail.put(acc.Id, acc.OwnerId);
}
Map<ID> mapUsers = new Map<ID>([SELECT Email FROM User WHERE Id IN:mapOwnerEmail.values()]);
for (Account acc : Trigger.new){
// map gets the account owner email
acc.field_Name__c = mapUsers.get(mapOwnerEmail.get(acc.Id)).Email;
}
}
All Answers
Hi,
trigger insertEmailMap on Account (before insert, before update) {
Map<Id,Id> mapOwnerEmail = new Map<Id,Id>();
for (Account acc : Trigger.new){
mapOwnerEmail.put(acc.Id, acc.OwnerId);
}
Map<ID> mapUsers = new Map<ID>([SELECT Email FROM User WHERE Id IN:mapOwnerEmail.values()]);
for (Account acc : Trigger.new){
// map gets the account owner email
acc.field_Name__c = mapUsers.get(mapOwnerEmail.get(acc.Id)).Email;
}
}
Your question isn't too clear and I'm not sure what you're REALLY trying to do. If all you want to do is build a map with the email address of the account(s) owner(s) this will work. I've simplified the code a bit.
However, I'm not sure that's what you're asking. Please clarify if it's not . Prepopulating the owner's email is kind of redundant though since you'll already have it via the ownerId reference.
Thank you for all your answers. While trying to avoid SOQL statements in for loops the following code I gather from all your answers. This could be trim somewhere, I am not sure though.
Yep, that's the code you should use. Mine didn't take limits into accout.