0

Im learning about Future methods so wanted to covert my triggerHandler method to Future method...where Im trying to insert contact on every user insert. but im getting an issue called "Future methods do not support parameter type of List" and then I got to know that we cannot pass Sobject as Parameters.....so can anyone help to pass List in Future Method

Sharing my code :

    Trigger:
    trigger BeforeInsertUseronCondeleteTrigger on User (before Insert , after Insert) {
        if(Trigger.isBefore && Trigger.isInsert) {
            BeforeInsertUseronCondeleteHandler.PreventContactAddition(Trigger.new);
        }
         if(Trigger.isAfter && Trigger.isInsert) {
            BeforeInsertUseronCondeleteHandler.PreventContactAddition(Trigger.new);
        }
    }

Handler:
public class BeforeInsertUseronCondeleteHandler {
    @future
    public static void PreventContactAddition(List<User> newList){
        Set<String> emailSet = new Set<String>();
        List<Contact> contact = new List<Contact>();
        Final String errMsg = 'The email already exists on another Record: ';
        
        for( User u : newList ) emailSet.add( u.Email );
        Map< String, Id > duplicateContactMap = new Map< String, Id >();
        
        for( Contact c : [select Id, Email from Contact where Email = :emailSet] )
            duplicateContactMap.put( c.Email, c.Id );
        
        for( User u : newList ){
            Id duplicateContactId = duplicateContactMap.get( u.Email );
            if( duplicateContactId != null ){
                u.addError( errMsg + duplicateContactId );
            }
            else if( Trigger.isAfter && Trigger.isInsert) {
                Contact con = new Contact(LastName = u.LastName,OwnerId=u.Id, Email=u.Email);
                contact.add(con);
            }
        }
        
        Insert contact;
    }
}
1
  • 1
    Please note that in a future method you cannot use addError. It only works on record from trigger context. Once you go async (future or queueable), you will not be in trigger context anymore.
    – RubenDG
    Aug 29, 2023 at 11:20

1 Answer 1

0

For After Insert-->

Pass list of record Id to future method. Query records in future method using these Ids.

Else use below solution

https://www.mstsolutions.com/technical/passing-sobject-to-future-methods-in-salesforce/

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .