+ Start a Discussion
Ryan ReeseRyan Reese 

Code help

When an opportunity closes to won, I want a chatter update to a specified chatter group (which i dont have listed)
I tried editing this code from someone but need some assistance

trigger OppWonChatter on Opportunity (after insert, after update) {

String status;
String OppAccName;
String OppOwnerName;
FeedItem post = new FeedItem();
    
    for(Opportunity o : Trigger.new) {
        if(o.OwnerId == '00560000001MxXV') { //It will not post record for for this user to group. changed last letter to cap v so i can test
            return;
        }
        else {
            if(Trigger.isInsert ) {
                if( o.IsWon == true ) { //This will be executed on new record insertion
                    for (Opportunity oppty : [SELECT Account.Name, Owner.Name FROM Opportunity WHERE Id =:o.Id] ) {
                        OppAccName = oppty.Account.Name;
                        OppOwnerName = oppty.Owner.Name;
                    }    
                    status = OppOwnerName + ' just won ' + OppAccName + ' for ' + o.expectedrevenue + '!';

                    
                    post.ParentId = OppAccName;
                    post.Title = o.Name;
                    post.Body = status;
                    
                    insert post;
                }
            }    
            else {
                if ( Trigger.isUpdate ) {
                    if( o.IsWon == true && Trigger.oldMap.get(o.id).IsWon == false) { //This will be executed on update to existing record
                        for (Opportunity oppty : [SELECT Account.Name, Owner.Name FROM Opportunity WHERE Id =:o.Id] ) {
                            OppAccName = oppty.Account.Name;
                            OppOwnerName = oppty.Owner.Name;
                        }    
                        status = OppOwnerName + ' just won ' + OppAccName + '!';
                            
                        post.ParentId = OppAccName;
                        post.Title = o.Name;
                        post.Body = status;
                        
                        insert post;      
                    }
                }
            }
        }
    }    
}
dbakedbake
I would suggest simplifying this code and also taking the SOQL statement out of the loop because it could fail if a bulk update was done.

But to answer your question, I think the issue is with line 'post.ParentId = OppAccName'. post.ParentId is the place where you want to post to go. So if you were using o.Id, it would be in the Opportunity feed, but you need to put the Chatter Group Id in that field so 'post.ParentId = <whatever the Chatter Group Id is> for those lines and it should work. You could hardcode the id, but I would suggest doing a query for the id before you start the for loop.

Please mark as solved if this answers your question or comment back if I can be of more assistance.