0

please help.

I am new to SFDC please help.

Requirement: Restrict user deactivation if Account is owned by the user and send an Email with details.

Trigger on user object:

    trigger userTrigger on User (before insert,before update) 
   {
    switch on Trigger.operationType
    {
        when Before_update
        {
            List<User> userList = Trigger.new;
            for(User currentUser: userList)
            {
                if(currentUser.isActive==false)
                {
                    List<Account> acc=[Select id, Name from Account where ownerId =:currentUser.Id];
                    if(Acc.size()>0)
                    {
                        currentUser.addError('Users owns Account please handle before deactivating: Accounts owned '+Acc.size());
                        System.debug('Reached here');
                        userTriggerHandler.sendDetails(currentUser.Id);
                    }
                }
            }
        }
    }
}

Trigger Handler:

public class userTriggerHandler 
{
    @future
    public static void sendDetails(id currId)
    {
        System.debug('send Details called');
        Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
        message.toAddresses = new String[] { 'dummy@mail.com' };
        message.optOutPolicy = 'FILTER';
        message.subject = 'Dummy Subject';
        message.plainTextBody = 'This is the message body.';
        Messaging.SingleEmailMessage[] messages =   new List<Messaging.SingleEmailMessage> {message};
        Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);
        
        if(results[0].Success)
        {
            System.debug('Mail Sent!');
        }
        
        //Try-Catch will be used for Exception handling
    }
}

If I am not using @future annotation I am getting MixedDML Exception as I am using Setup and Nonsetup object, I guess.

And If I am using future annotation this method is not getting called.

Can I please be helped with this, Thank you. Can you suggest any other best practice?

Your Answer

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

Browse other questions tagged or ask your own question.