i am trying to copy values from a custom field in account object and trying to create topics based on those values. Trigger is working fine. But if there are any old Topics are inserting then it is throwing error.
Error: Invalid Data. Review all error messages below to correct your data. Apex trigger InsertTopic caused an unexpected exception, contact your administrator: InsertTopic: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATE_VALUE, A topic with the name, 54644, already exists.: [Name]: Trigger.InsertTopic: line 19, column 1
trigger InsertTopic on Account (after insert) {
List<TopicAssignment> taList = new List<TopicAssignment>();
List<TopicAssignment> taList1 = new List<TopicAssignment>();
List<Topic> topicList= new List<Topic>();
for(Account c : trigger.new)
{
String d1= c.Topics__c; // Custom field on Account Object.
system.debug('aaaaaaaaaa'+d1);
String[] d= d1.split('\\s*,\\s*');
for(String s: d)
{
Topic ta1 = new Topic();
ta1.Name=s;
topicList.add(ta1);
}
system.debug('aaaaaaaaaa'+topicList);
insert topicList;
for(Topic s1: topicList)
{
TopicAssignment ta = new TopicAssignment();
ta.TopicId=s1.Id;
taList.add(ta);
ta.EntityId = c.Id;
}
insert taList;
}
}
How can i overcome that error and still need that topic to be assigned to the record. Any ideas?