I am new to salesforce can anyone help me with the trigger. I have tried it but not able to fulfill the requirement. Please help me any suggestions are appreciated. Requirement: A company wants to do collaboration using chatter group for project. Whenever Enable Collaboration checkbox is checked a respective chatter group should be created. Note: Only one chatter group should exist for a Project.
Trigger:
trigger ChatterGroupCreation on Project__c (after insert,after update) {
if(Trigger.isAfter && Trigger.isInsert){
ChatterGroupCreationHandler.isProjectInsert(Trigger.new);
}
if(Trigger.isAfter && Trigger.isUpdate){
ChatterGroupCreationHandler.isProjectUpdate(Trigger.new,Trigger.oldMap);
}
Handler:
public class ChatterGroupCreationHandler {
static set<Id> projecthavingchatter=new set<Id>();
public static void isProjectInsert(List<Project__c> listProject){
System.debug('listProject'+listProject);
List<CollaborationGroup> chattergroup=new List<CollaborationGroup>();
for(Project__c proj:listProject){
if(proj.Enable_Collaboration__c==true){
CollaborationGroup myGroup = new CollaborationGroup();
myGroup.Name=proj.Name+proj.Id;
myGroup.CollaborationType='Public';
chattergroup.add(myGroup);
projecthavingchatter.add(proj.Id);
}
}
System.debug('projecthavingchatter'+projecthavingchatter);
System.debug('chatter'+chattergroup);
insert chattergroup;
}
public static void isProjectUpdate(List<Project__c> listProject,Map<Id,Project__c>oldMapProject){
System.debug('projecthavingchatter'+projecthavingchatter);
List<CollaborationGroup> chattergroup=new List<CollaborationGroup>();
for(Project__c proj:listProject){
Project__c oldProj=oldMapProject.get(proj.Id);
if(oldProj.Enable_Collaboration__c==false && proj.Enable_Collaboration__c==true && !projecthavingchatter.contains(proj.Id)){
CollaborationGroup myGroup = new CollaborationGroup();
myGroup.Name=proj.Name+proj.Id;
myGroup.CollaborationType='Public';
chattergroup.add(myGroup);
}
}
system.debug('chatter update'+chattergroup);
try{
insert chattergroup;
}
catch(Exception e){
}
}
}
The problem is if I have created 2-3 projects of same name then I cannot create a different chatter group for each. And also whenever I turn the checkbox from false to true in update it should check if there is chatter group created or not. Please help me. I have updated the code based on your suggestions can anyone tell me if its correct or not