function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
RbnRbn 

Duplicate Records getting Inserted on Edit

I have a trigger which inserts record in The public Groups.

 

But when i edit the records a new record is getting inserted(which should not happen).

 

Below is the Trigger:

trigger GroupCreation on IA_Team__c (after insert,after update)
{
Group grp = new Group();
list<Group> gplist=new list<Group>();
for(IA_Team__c ia:trigger.new){
grp.Name = ia.Name;
grp.DeveloperName = ia.Public_Group_Name__c;
gplist.add(grp);
}

insert gplist;

}

 

souvik9086souvik9086

So then remove after update from the trigger event.

 

If the post helps you, please throw KUDOS.

Thanks

Grazitti InteractiveGrazitti Interactive

Hi,

 

You should not remove after update because after update of every IA_Team__c corresponding Group record should be updated also.

 

There are two way to handle this.

 

1. use upsert rather than insert

 

trigger GroupCreation on IA_Team__c (after insert,after update)
{
Group grp = new Group();
list<Group> gplist=new list<Group>();
for(IA_Team__c ia:trigger.new){
grp.Name = ia.Name;
grp.DeveloperName = ia.Public_Group_Name__c;
gplist.add(grp);
}

upsert gplist;

}

 

2. 

 

trigger GroupCreation on IA_Team__c (after insert,after update)
{
Group grp = new Group();
list<Group> gplisttoInsert =new list<Group>();

list<Group> gplisttoUpdate =new list<Group>();

Set<String> names = Set<String>();

Set<String> developrs = Set<String>();

for(IA_Team__c ia:trigger.new){

     names.add(ia.Name);

     developrs .add(ia.Public_Group_Name__c);

}

Map<String,Group> oldGrp = new Map<String,Group>();

for(Group grp : [select DeveloperName,Name From Group where Name IN :names and DeveloperName IN :developrs  ]){

   oldGrp.put(grp.DeveloperName,grp);

}

 

for(IA_Team__c ia:trigger.new){

if(oldGrp.containsKey(ia.Public_Group_Name__c)){
    oldGrp.get(ia.Public_Group_Name__c).Name = ia.Name;
    oldGrp.get(ia.Public_Group_Name__c).DeveloperName = ia.Public_Group_Name__c;

    gplisttoUpdate.add(oldGrp.get(ia.Public_Group_Name__c));

}else {

     grp.Name = ia.Name;
     grp.DeveloperName = ia.Public_Group_Name__c;

     gplisttoInsert.add(grp);

}

}

if(!gplisttoInsert.isEmpty())

insert gplisttoInsert

if(!gplisttoUpdate.isEmpty())

update gplisttoUpdate

 

}

 

 If the post helps you, please throw KUDOS.

 

Thanks,

www.grazitti.com

 

Raj_Raj_

you need to remove update or you can use like this 

 

trigger GroupCreation on IA_Team__c (after insert,after update)
{
if(Trigger.isInsert){ Group grp = new Group(); list<Group> gplist=new list<Group>(); for(IA_Team__c ia:trigger.new)
{ grp.Name = ia.Name; grp.DeveloperName = ia.Public_Group_Name__c; gplist.add(grp); }
}
insert gplist;
}

Thanks 

Raj