You need to sign in to do that
Don't have an account?

Trigger to capture changed Account name into a string for comparrison and send in an email.
I'm trying to capture the new and old contact Account names into string fields for string comparrison, and sending in an email. The code below is a test trigger on a contact record. The email sent to me after changing the contact's account to another give me values of null. If I do this, for example, with the c.Title field I don't have this issue, I can pull the value into a string.
The email message: "Account field changed: Old Account: null New Account null"
Thanks for any help.
Kevin
================
The trigger:
trigger EmailAccountName on Contact (after update) {
string OldAccount;
string NewAccount;
for (Contact c : Trigger.old) {
OldAccount = c.account.name;
}
for (Contact c : Trigger.new) {
NewAccount = c.account.name;
}
// Send Email Notification
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {'my email address'};
mail.setToAddresses(toAddresses);
mail.setReplyTo('my email address');
mail.setSenderDisplayName('Me');
mail.setSubject('Alumni Contact Information has changed.');
mail.setBccSender(false);
mail.setUseSignature(false);
mail.setHtmlBody('Account field changed: Old Account: ' + OldAccount + ' New Account ' + NewAccount );
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
You'll probably want to make some changes to check for a change in AccountID so that you aren't querying Accounts related to Contacts that haven't changed.
All Answers
If this is a trigger on Contact, you'll need to query for the Account values as they aren't available in this context.
Basically, you'll want to collect up all the AccountIDs (where the accountId has changed) in a set or list then query the Account table and dump the results into a Map<Id,Account>. Then you can go through your contacts again and check the names by referencing the map of Accounts.
Thanks davidjgriff. I believe I found an example of how to query the contact's accounts.
Can you tell me how I'd assign the Account name to the NewAccount string?
Thanks
Kevin
================
trigger EmailAccountNameTest on Contact (after update) {
String NewAccount;
Set<Id> accIds=new Set<id>();
for (Contact con : trigger.new) {
accIds.add(con.accountId);
}
Map<id, account> accMap=new Map<id, account>();
accMap.putAll([select id, Name from Account where id in :accIds]);
for (Contact c : Trigger.new) {
NewAccount = c.account.ID;
}
You'll probably want to make some changes to check for a change in AccountID so that you aren't querying Accounts related to Contacts that haven't changed.