I have written some code which create tasks whenever I create a new staff record based on some conditions.


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); 

    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

  • Can you edit your post to make your question more clear? Your title indicates that you are creating too many records, but in the post itself you indicate it is creating too few. You also haven't really explained your requirements.
    – Adrian Larson
    Commented Oct 25, 2016 at 15:26
  • Yes Andrain. I did that. Please check it now
    – KSL
    Commented Oct 25, 2016 at 15:38

1 Answer 1


You're creating new records each time around, on every insert and update. Just clicking Edit and Save will cause more records to appear. Instead, you can either query for existing records, or to save a query, you can just check for differences.

Map<Id, Set<String>> jobs = new Map<Id, Set<String>>();
Set<String> allJobNames = new Set<String>();

for(Integer index = 0, size = Trigger.new.size(); index < size; index++) {
        oldRec = Trigger.isInsert? new Staff__c(): Trigger.old[index],
        newRec = Trigger.new[index];
        oldJobs = new Set<String>((oldRec.Groups__c==null? '': oldRec.Groups__c).split(';')),
        newJobs = new Set<String>((newRec.Groups__c==null? '': newRec.Groups__c).split(';'));
    jobs.put(Trigger.new[index].Id, newJobs);

At this point, you now have a list of jobs for each staff entry that are new since the last time your code ran. Note that this code is bulkified, so it can support any number of records per transaction (currently limited to 200).

Next, you need to get all of the groups you're interested in:

Map<String, List<GroupMember>> membersByGroupName = new Map<String, List<GroupMember>>();
for(String jobName: allJobNames) {
    membersByGroupName.put(jobName, new GroupMember[0]);
for(GroupMember record: [SELECT Group.DeveloperName, UserOrGroupId FROM GroupMember WHERE Group.DeveloperName = :allJobNames]) {

Finally, you just need to build your tasks:

Task[] newTasks = new Task[0];
for(Id staffRecordId: jobs.keySet()) {
    Set<Id> userIds = new Set<Id>();
    for(String jobName: jobs.get(staffRecordId)) {
        for(GroupMember member: membersByGroupName.get(jobName)) {
            if(!userIds.contains(member.UserOrGroupId)) {
                // Create tasks here
insert newTasks;

Other notes:

You never need to check if the results of a query are null.

Account[] a = [SELECT Id FROM Account LIMIT 5];

a is guaranteed to be a list, not a null value.

Iterating over an empty loop is harmless.

String[] strings = new String[0];
for(String value: strings) {

This code will run without error, because a list with zero elements results in a for-loop that runs zero times.

Empty DML operations don't count against you.

Account[] a = new Account[0];
for(Integer i = 0; i < 200; i++) {
    insert a;

This code runs without error in a fairly trivial amount of time, because no records are being inserted, so no governor limits are broken. More to the point, it's okay to insert a list without checking if it's empty.

  • Thank you so much... It helped a lot.. I will try not to ask these questions again and resolve it myself. once again thank you so much for your suggestions and help
    – KSL
    Commented Oct 25, 2016 at 18:48
  • @KSL it's okay to ask, as long as you learn something new! We're definitely here to help.
    – sfdcfox
    Commented Oct 25, 2016 at 19:02
  • Thanks. I checked it and it gave one new issue. If group A and B has the same user, we shouldn't allow to create a two different tasks and it should be only one task per user. currently the above code is allowing us to create a new task. Is there anyway to fix that
    – KSL
    Commented Oct 25, 2016 at 21:12
  • Can you please check my comment once. I checked it and it gave one new issue. If group A and B has the same user, we shouldn't allow to create a two different tasks and it should be only one task per user. currently the above code is allowing us to create a new task. Is there anyway to fix that
    – KSL
    Commented Oct 25, 2016 at 22:35
  • @KSL You can maintain a set of user Ids that have already been used. I've edited in an example. Feel free to adjust this as you need to.
    – sfdcfox
    Commented Oct 25, 2016 at 23:06

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .