0

How can I update an account field called "Last_Contact" when an email is sent from the account with the created data of that email? I tried doing it via a field update and starting building the trigger but I've hit a wall. Thanks!

Use case: When I open account ABC co. and send an email from the activity history related list i would like a field on the account called Last_Contact to update with the date the email was sent (which would be the current date).

Thanks!

0

Going from your use case given, this trigger will overwrite the timestamp each time an email is sent from the Account. Should you handle multiple emails and possible updates to existing emails?

Anyway, code..

trigger AccountEmail on EmailMessage (before insert) {

    Set<Id> accountIds = new Set<Id>();
    for(EmailMessage message : Trigger.new) {
        if (message.RelatedToId.getsobjecttype().getDescribe().getName() == 'Account') {
            accountIds.add(message.RelatedToId);
        }
    }

    List<Account> accountsToUpdate = [
        select id,
            Last_Contact
        from Account
        where id in :accountIds];

    for (Account account : accountsToUpdate) {
        account.Last_Contact = Date.today();
    }
    update accountsToUpdate;
}

The getsobjecttype().getDescribe().getName() call is used to make sure the global EmailMessgae object triggered is only being worked on if it has a RelatedToId of object type Account.

The SOQL and DML will only run when your Account set has a value, the previous object checking will prevent unnecessary limit usage.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.