Friday, 6 March 2015

Trigger that posts to Chatter automatically

The problem

Posting to Chatter via Apex Trigger

This requirement comes up fairly regularly now - saving users time by automatically posting to Chatter if an update happens within Salesforce that needs calling out.

Examples could be - An urgent case has come in - a customer account has gone Red - there is a service issue etc.

This particular chatter trigger looks for any cases marked with a skill of "Escalation" and automatically posts it out on Chatter with a Topic tag marked "Escalation".

To implement this trigger in your ORG you would need to add a field called "Skills__c" on your Case object and populate it with "Escalation" when you insert a new case.

trigger EscalationPost on Case (after insert) {
//Only firing trigger on initial case creation - amend if requirement to before update etc
    for(Case myCase: Trigger.new){
        if(myCase.Skills__c=='Escalation')
//Change criteria of trigger if required
        {
            FeedItem post = new FeedItem();
            post.ParentId = myCase.id;
//Change body of Chatter post in between single speech marks below
            post.Body = 'Escalated Complaint Case! Retention team need to engage. [#Escalation]';
            insert post; 
        } //end if
    } //end for loop
} // end trigger