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
Alistair Field 8Alistair Field 8 

How can I automatically add a topic to a certain feed type.

I would like to automatically add a topic to Question asked in the Community.
I have the following apex trigger that works for all posts. But I would like to add in a statement that ONLY makes it works on Question type posts on a community and not internal org.

Thanks in advance.
trigger AddingQtopic on FeedItem (after insert) {
      List<TopicAssignment> taList = new List<TopicAssignment>();
    for(FeedItem c : trigger.new){
  TopicAssignment ta = new TopicAssignment();
  ta.TopicId = '0TO400000000NCE';
  ta.EntityId = c.Id;  
        taList.add(ta);
    
    insert taList;    
        }
    }

 
Raja Kumar PallepatiRaja Kumar Pallepati
Hello, 
Please find sample code for question type posts.
Apex Trigger:
trigger FeedItemTrigger on FeedItem (after insert) {
    if(Trigger.isAfter && Trigger.isInsert)
        FeedItemHelper.doInsert(Trigger.new, 'HelpDesk', 'QuestionPost');
}
 
Apex Class:
public class FeedItemHelper {
    public static void doInsert(List<FeedItem> newfeeds, String topicName, String topicType) {
        List<Topic> topicsExt = new List<Topic>();
        topicsExt = [SELECT Id FROM Topic WHERE Name =:topicName LIMIT 1];
        List<TopicAssignment> taList = new List<TopicAssignment>();
        if(!topicsExt.isEmpty()) {
            for(FeedItem item: newfeeds) {
                if(item.type == topictype) {
                    taList.add(new TopicAssignment(TopicId = topicsExt[0].Id,
                                         EntityId = item.Id ));
                }
            }
        }    
        if(!taList.isEmpty()) {
            insert taList;
        }
    }
}