Salesforce Developers Blog

Triggers on User Creation

Avatar for Jon MountjoyJon Mountjoy
You need to use @future when creating a trigger on a User, sometimes.
March 09, 2010
Listen to this article
0:00 / 0:00

I’ve just been trying to figure out how to trigger some action on User creation. For example, imagine you want to make sure that a new user automatically follows some important folk in Chatter! (signed up yet?) It turns out to be a little tricky because the User object is a little special.

The documentation states that some objects “require that you perform DML operations on only one type per transaction” – the User object is one of these objects. So if I want to manipulate other objects (I do), I have to use a second method (that uses a @future).

Here’s the basic outline of what I did. Here’s the trigger, on a after insert of a User object:

1// A trigger that will get called after a new user is created.
2// It simply invokes a helper method that does the work asynchronously.
3trigger addFriendsToUser on User (after insert) {
4ChatterUtils.addFriendsToUsers (Trigger.newMap.keySet());
5}

Now all we need is to make sure that the addFriendstoUsers() uses the @future annotation:

1// A helper class
2public class ChatterUtils {
3// This method is called by the addFriendsToUser trigger on the User object, essentially allowing us to automatically
4// add a number of friends to a new User.  The method is run asynchronously.
5@future public static void addFriendsToUsers(Set  userIDs) {
6List users = [select ID from User where ID IN :userIDs];
7for (User u: users) {
8// Test Code.  Replace with whatever code delights and excites
9TestO__c t = new TestO__c();
10t.userid__c = u.id;
11insert t;
12}
13}
14}

As you can see, I’m not actually befriending the user – but I do create another record just to test that this all works. Which it appears to do!

Postscript