I have written some code which create tasks whenever I create a new staff record based on some conditions.
Trigger:
trigger triggerTaskImplemetationonJob on Staff__c (before insert, before update) {
List<Task> taskList = new List<Task>();
List<Staff__c> jobList = trigger.New;
String[] groupNames = jobList[0].Group__c != null
? jobList[0].Group__c.split(';')
: new List<String>();
system.debug('groupNames :::' + groupNames);
list<GroupMember> gm = [select group.name,group.DeveloperName,UserOrGroupId from GroupMember where group.DeveloperName =: groupNames];
List<Task> tasks = new List<Task>();
system.debug('developerName ::' + group.DeveloperName);
system.debug('*****group****'+gm);
for(Staff__c jobObj : jobList){
if(gm != null && gm.size() > 0){
for(GroupMember g : gm){
taskList.add(new Task(
ActivityDate = Date.today(),
WhatID = jobObj.Id,
ownerID = g.UserOrGroupId,
Status = 'Open',
type = 'Other',
Priority = 'Normal'
}
}
}
if(taskList.size() > 0)
insert taskList;
}
The group__c
is a multi picklist field and which is allows me to select multiple public groups and create tasks to the users in those public groups
Ex: I have three group . A, B, C group A holds X,Y as users group B holds Z as users group C holds P,Q as users
Whenver I create a new staff recording by selecting the group names from mutliple picklist field ( ex: I seleted A, B for the first time) and it created 3 tasks for me . Now I added one more picklist value ( I added group C also) and saved the record. In this time, it is suppose to create only 2 more tasks, but its created 5 new tasks in those 3 are already exists.
I don't want to create duplicate tasks in this case. I know that I am not checking some condition and which is causing the duplicate record creation. Please help me how to fix it