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:
// A trigger that will get called after a new user is created.
// It simply invokes a helper method that does the work asynchronously.
trigger addFriendsToUser on User (after insert) {
ChatterUtils.addFriendsToUsers (Trigger.newMap.keySet());
}
Now all we need is to make sure that the addFriendstoUsers()
uses the @future
annotation:
// A helper class
public class ChatterUtils {
// This method is called by the addFriendsToUser trigger on the User object, essentially allowing us to automatically
// add a number of friends to a new User. The method is run asynchronously.
@future public static void addFriendsToUsers(Set userIDs) {
List users = [select ID from User where ID IN :userIDs];
for (User u: users) {
// Test Code. Replace with whatever code delights and excites
TestO__c t = new TestO__c();
t.userid__c = u.id;
insert t;
}
}
}
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
- Don’t forget about the Chatter Developer Preview Tech Talk on March 15
- Check out the An Introduction to Salesforce Chatter article for some real Chatter code snippets