function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Sam EpsteinSam Epstein 

Reference Object Field in Chatter Apex Trigger

Hi Everyone,

I have a chatter apex trigger that fires everytime there is an update to a field in my field set on my account obect. However, I want to reference the account name and the url as well as bolding/underlining the text in the chatter post. 

What would be the best way to do that?

Here is my code:
 
trigger AccountChatter on Account (after update) {
    List<Schema.FieldSetMember> lstTrackedFields = SObjectType.Account.FieldSets.AccountChatter.getFields();

    if (lstTrackedFields.isEmpty()) return;
    
    List<FeedItem> lstFieldChanges = new List<FeedItem>();
    
    if(!trigger.isUpdate) return;
    
    for (Account objNewAccount : trigger.new) {
        String chatterPostBody = '';
        final Account oldAccount = trigger.oldmap.get(objNewAccount.Id);
        // Iterate over all fields in Fieldset
        for (Schema.FieldSetMember objField : lstTrackedFields) {
            String fieldName  = objField.getFieldPath();
            String fieldLabel = objField.getLabel();          	

            if (objNewAccount.get(fieldName) == oldAccount.get(fieldName))
                continue;

            String oldValue = String.valueOf(oldAccount.get(fieldName));
            String newValue = String.valueOf(objNewAccount.get(fieldName));
     

            if (oldValue != null && oldValue.length()>255)
                oldValue = oldValue.substring(0,255);

            if (newValue != null && newValue.length()>255)
                newValue = newValue.substring(0,255); 
            
            chatterPostBody += UserInfo.getName()+' changed '+fieldLabel+' from '+oldValue +' to '+newValue+'\n'+'\n';       
        }
        if(String.isNotEmpty(chatterPostBody)){
            FeedItem post = new FeedItem();
            post.ParentId = objNewAccount.Id; // RecordId
            post.Body = chatterPostBody;
            
           
            FeedItem groupPost = new FeedItem();
            groupPost.ParentId = '0F94B0000008kd1SAA'; // GroupId
            groupPost.Body = chatterPostBody;
        
            lstFieldChanges.add(post);
            lstFieldChanges.add(groupPost);
        }
    }
    
  

    if (!lstFieldChanges.isEmpty()) insert lstFieldChanges;

}