I have a trigger on one of the custom objects which helps me to create a task based on one of the fields( active = true) in the custom object. I am able to achieve this requirement, but I have one more field(pick list) which holds to a list of public group names and whenever I create/edit my custom object with the above criteria, it should create the tasks to all users who are in the public group.
The code which I have written is,
trigger triggerTaskImplemetationon on Staff__c (before update) {
List<Task> taskList = new List<Task>();
List<Staff__c > jobList = trigger.New;
List<GroupMember> GMlist = new List<GroupMember>();
for(Staff__c jobObj: jobList){
if(jobObj.status == true){
taskList.add(new Task(
ActivityDate = Date.today(),
WhatID = jobObj.Id,
Status = 'Open',
type = 'Other'
));
}
}
insert taskList;
}
I have gone through the websites and forums and we can get the list of users based on below details
List<GroupMember> GMlist = new List<GroupMember>();
I am not sure how to implement in my code. Any suggestion would be helpful
Update:
I am able to read the users from public groups now and able to create tasks to the users in that group. Below is the updated code
trigger triggerTaskImplemetationonJob on Staff__c (before update) {
List<Task> taskList = new List<Task>();
List<Staff__c> jobList = trigger.New;
String groupNames = jobList[0].Group__c;
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;
}
But the problem is, the Group__c is a multi picklist field where user can select multiple groups at the same time and save the record. when we select multiple groups, the group names will come as A;B and the soql returns null and it wont create tasks after that.
Please let me know how to fix it.