You need to sign in to do that
Don't have an account?
SFDC Guest
Convert trigger into helper class with future method.
I have written a trigger to create a contact and assign it to Customer Community user as user.contactId whenever user is created from data loader. But I am getting mixed DML issue. I know that non setup and setup objects cannot be inserted. But please help how to convert below logic into future method in helper class. Thanks in advance.
Thanks.
trigger CreateContact on User (before insert) { List<User> listUser = new List<User>(); for (User usr : trigger.new) { if (String.isBlank(usr.contactId)) { listUser.add(usr); } } if (listUser.size() > 0) { List<Contact> newContacts = new List<Contact>(); Map<String, User> userNameMap = new Map<String, User>(); //Create Contact For Each User for (User usr : listUser) { String contactLastName = usr.lastname; userNameMap.put(contactLastName,usr); Contact con = new Contact(LastName = contactLastName, Description = 'this is created by AutoCreateAccount trigger'); newContacts.add(con); } Insert newContacts; for (Contact con : newContacts) { //Put Contact Id's on Contacts if (userNameMap.containsKey(con.Name)) { userNameMap.get(con.Name).contactId = con.Id; } } } }
Thanks.
You can try using the below code and let me know if there are any issues.
For additional reference you can check this link https://salesforce.stackexchange.com/questions/66104/converting-trigger-into-a-helper-class-trigger-dispatcher/66108
I hope this helps and in case if this comes handy can you please choose this as best answer so that it can be useful for others in the future.
Regards,
Anutej
Above code will give mixed DML issue. Please let me know how to write a future method in helper class. We cann't pass List<User> as parameter in future method.
>> https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_dml_non_mix_sobjects.htm
>>https://www.xgeek.net/salesforce/to-fix-mixed_dml_operation-errorsetup-and-non-setup-objects-in-salesforce/
Also, you could try checking this as this mentions a way to pass parameters to a future method:
>> https://www.salesforcehut.com/2020/02/simple-technique-to-pass-sobject-list.html