+ Start a Discussion
Todd B.Todd B. 

Trigger Creating Two Chatter Entries

I created the following trigger to create a chatter entry every time someone wins an opportunity

trigger CreateChatterEntry on Opportunity (before Update) {

For(opportunity opp : Trigger.new){

// Check to see if the Oppty was previously Marked Closed Won
Opportunity beforeUpdate = System.Trigger.oldMap.get(opp.Id);
if(beforeUpdate.IsWon != opp.IsWon){

    String ownerIds = opp.Oppty_Owner_Name__c;
    String oppName = opp.name;
    Set<ID> ownerId = new Set<ID>();
    Map<ID,User> userMap = new Map<ID,User>([SELECT ID, Name, FirstName FROM User WHERE ID In : ownerid]); //This is our user map
    User uName = userMap.get(opp.ownerId);
    // Get a list of All the Current Chatter Group Names
    List<CollaborationGroup> Grps = [Select Name, Id FROM CollaborationGroup];
    Map<string, String> GrpName = new Map<string, string>{};
    for(CollaborationGroup gn: Grps)
    // If the Oppty is marked Closed Won, Create Chatter entry.
    If(opp.iswon ==true){
        FeedItem fitem = new FeedItem ();
         fitem.type = 'LinkPost';
                fitem.ParentId = grpName.get('Salesforce.com Users');  //Select What Chatter group to post message in.
                fitem.LinkUrl = '/' + opp.id; //This is the url to take the user to the activity
                fitem.Title = oppName + ' Opportunity';  //This is the title that displays for the LinkUrl
                //fitem.Body = ('Congratulations to ' + uName.name + ' on winning ' + oppname + '!  Nice Job '+ uName.firstname+'.');
                fitem.Body = ('Congratulations to ' + uName.name + ' on winning ' + oppname + '!');
        Insert fitem;
    } } 

The problem is sometimes it creates one Chatter entry and sometimes it creates two postings.  

Also, is there any way to hard code in the posting making the post.  In this case I want all post to come from me.  That way it does not look like the sales person is patting themselves on the back buy being congratulated by me.
Hi Todd, 

To specify the Post going from a specific user, 

You could also specify a particular user by user Id:


See the below thread for the Duplicate posts,