I want to have it where if someone makes multiple field updates in one edit, it posts to chatter like this:
This is actually a pretty simple change. See where you have
FeedItem post = new FeedItem();
post.ParentId = objNewAccount.Id; // RecordId
post.Body = UserInfo.getName()+' changed '+fieldLabel+' from '+oldValue +' to '+newValue ;
lstFieldChanges.add(post);
inside the inner for
loop, which iterates field by field? You want that code to be in your outer for
loop, that iterates Account by Account.
However, you're also wanting to accumulate a post body that mentions all of the changed fields. You can do that using very similar logic to what you're working with now. The way I like to do it is to accumulate a List<String>
:
List<String> changeDetails = new List<String>(); // at top of outer for loop
and then in my inner for
loop
changeDetails.add(fieldLabel+' from '+oldValue +' to '+newValue);
This allows you to efficiently template the final post body with String.format()
when you're back at the bottom of your outer loop:
post.Body = String.format(
'{} made the following changes:\n{}',
new List<String> {
UserInfo.getName(),
String.join(changeDetails, '\n')
}
);
If also possible, can I add to the trigger so that it posts to a specific group or user? The reason why I'm writing a trigger is that we need to track more than 20 fields on a record.
Sure. Just change the ParentId
of the feed item. You may want to amend the message to include details of the changed record. See the FeedItem reference under ParentId
:
ID of the object type to which the FeedItem object is related. For example, set this field to a UserId to post to someone’s profile feed, or an AccountId to post to a specific account.
Best Answer
You can use the Chatter REST API to access Chatter but you will need a user context with which to access / post information.
http://www.salesforce.com/us/developer/docs/chatterapi/
If your intention is merely to display a read only chatter feed then you can get away with an integration user and use the Chatter REST API to display the feed.
If you however want users to be able to post you will need to take care of the authentication via oauth or similar and then have salesforce users set up for all those who intend accessing.
If the users of this external website and Single Signed into Salesforce you could probably get away with embedding an Iframe which uses their already established session with salesforce to display a Chatter Feed