[SalesForce] Trigger – update Case field based on FeedItem

Apex newbie quest continues.

When new Chatter comment is added to Case, custom field on Case should be populated with information from latest Chatter comment.

Currently I have developed a 'before update' trigger on Case. It works quite well and suits my requirements, however works only when a Case is updated (doh). Now I want to make this solution a bit more "good-looking" and create "after insert" trigger on FeedItem object.

So far I have managed to identify that FeedItem is related to Case using parentId field (using code mentioned here as a sample – http://www.salesforcefast.com/2012/02/get-object-name-from-record-id.html).

However, I don`t know how to update information on Case from FeedItem trigger knowing only Case id (which is FeedItem parentId). Can anyone point me to the right direction? Thanks.

Best Answer

I suggest code like this:

trigger MyTrigger on FeedItem (after insert) {
    List<Case> updates = new List<Case>();
    for (FeedItem fi : Trigger.new) {
        if (fi.ParentId.getSObjectType() == Case.SObjectType) {
            updates.add(new Case(
                    Id = fi.ParentId,
                    ??? = fi.???
                    ));
        }
    }
    update updates;
}

It checks that the FeedItem is related to a Case and uses the update pattern that does not involve a query.

Related Topic