Saturday, 12 November 2011

Automatically Add User to Chatter Group

Following on from an earlier blog post that dealt with user autofollowing, I was recently asked about automatically adding users to a chatter group.  Here at BrightGen we have a chatter group that everyone gets added to when a user is created for them on our Salesforce instance.  Its not too arduous to add these users to the group, but every now and then one gets overlooked.

Chatter groups are stored as CollaborationGroup records, with the members of the group stored in CollaborationGroupMember records related via the CollaborationGroupId field.

The first step is to create a trigger that is executed wheh a user record is added.  I've reused the trigger I created for my autofollow user post:


trigger ai_user on User (after insert) 
{
 ChatterAutofollow.AutofollowUsers(trigger.newMap.keySet());
 ChatterAutoFollow.AddToGroups(trigger.newMap.keySet());
}

The second line, containing the call to the AddToGroups is the new part - this is the method that does the heavy lifting.

@future
public static void AddToGroups(Set<Id> userIds)
{
 List<User> users=[select id, Username from User where id in :userIds];
 
 // set up the groups that the user should be added to
 List<String> groups=new List<String>{'All Users'};
 
    List<CollaborationGroup> chatterGroups=[select id, Name from CollaborationGroup where name in :groups];

 List<CollaborationGroupMember> chatterGroupMembers=new List<CollaborationGroupMember>();
 List<FeedPost> feedPosts=new List<FeedPost>();
      
     // loop the users that have been created
     for (User user : users)
     {
                // loop the groups
      for (CollaborationGroup chatterGroup : chatterGroups)
      {
                        // add the user to the group
   CollaborationGroupMember cand = 
       new CollaborationGroupMember(
                      CollaborationGroupId=chatterGroup.id,
                            MemberId = user.Id);
       chatterGroupMembers.add(cand);
                        // announce this!
          FeedPost fpost = new FeedPost(ParentId=chatterGroup.id,
                Body = user.username + ' added to group via Bob Buzzard trigger');
                    feedPosts.add(fpost);
          fpost = new FeedPost(ParentId=user.id,
                    Body = 'You have been added to the ' + chatterGroup.name + ' group via Bob Buzzard trigger');
                  feedPosts.add(fpost);
  }
 }
    
 insert chatterGroupMembers;
 insert feedPosts;
}

as before, the method has to be declared with the @future annotation, as the trigger is invoked when a User is inserted and I'll otherwise hit mixed mode DML problems.

The group name is hardcoded for the purposes of this blog - not a good idea in practice and for a production system I'd store this information in a custom setting.  Once the groups have been retrieved, the inserted users are iterated and added to each of the groups.  As an added flourish I've added a post to the group to notify members the new user has joined, and a post to the new user's feed to let them know this has happened.  As I'm keen to grab all the credit that is going, I've also mentioned in each post that this was done via my trigger!

Now I can add a user via the UI:


Once the user is created, they are automatically added to the All Users group and a post announces this:


And navigating to the new users profile, shows a post on their chatter feed informing them this has taken place:


And finally, a shout out to my BrightGen colleage Zak Crammond who asked the question that led to this post.

15 comments:

  1. Hi Bob,

    Thanks for sharing this great feature, would this also work when the user is created thru the Dataloader.

    Thanks!

    ReplyDelete
  2. Hi Sam,

    Yes, as triggers fire when records are created via the data loader this would work in that scenario. It is built to handle bulk inserts so that shouldn't be a problem either.

    ReplyDelete
  3. hey bob getting some compile error.please help
    Error: Compile Error: Invalid type: FeedPost

    ReplyDelete
  4. Hey Bob,

    how to add a user to a public group ?

    ReplyDelete
  5. How to add users to a public group?

    ReplyDelete
    Replies
    1. Check out this thread on the developerforce boards:

      http://boards.developerforce.com/t5/Apex-Code-Development/Adding-User-to-Public-Group/td-p/178593

      Delete
  6. Oh Thanks.....that is a quick reply , i will check that post .

    ReplyDelete
  7. Thanks for sharing this thought.

    Ramadhar Mishra

    ReplyDelete
  8. how to call this in a class

    ReplyDelete
    Replies
    1. It depends on your exact use case, but the @future method can be called from a class just like any other method.

      Delete
  9. Hi Bob,

    I used this code in my Org and every one loved it , just want to say thanks to you . And one issue i saw was with the versions so i had used API version 20.0 instead of 27.0 But i have a fear would that allow me to deploy this code to production. Any thoughts?

    Thanks
    Akhil

    ReplyDelete
  10. Bob: Do you know if Salesforce has made this functionality configuration yet? We used to have a trigger on the user object (similar to yours) but we deactivated it. However, users are still being added to an "All xx Group" and we aren't sure why.

    ReplyDelete
    Replies
    1. Not that I'm aware of. There is still an idea open for this which hasn't had any updates from product management - I'd expect that to say delivered if they had changed it.

      Delete
  11. Hey Bob, i followed your guide but having trouble getting it working.... doesnnt seem to save anything?

    wrote it up on stackexchange if you have a chance to take a look to see if you can see whats wrong would love the input

    thanks for all the tutorials, very helpful stuff

    http://salesforce.stackexchange.com/questions/19181/add-new-user-to-chatter-group-automatically-not-working

    ReplyDelete
    Replies
    1. Looks like the issue here is limited to users who "self register" on the site as when the trigger runs they dont have the proper permissions. Any suggestions?

      Delete