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
Denis O'LearyDenis O'Leary 

apex trigger duplicates inserts

Can anyone help with the below:

I'm trying to stop this trigger from creating an extra object every time the Opportunity page is updated.


trigger createPMPage on Opportunity (after update) {

    List <Project_Management__c> PMInsert  = new List <Project_Management__c> ();
  
 
for (Opportunity o : Trigger.new)
    {
         Project_Management__c p = new Project_Management__c ();


  if (o.Job_Type__c == '1' )
    
        {
   p.Project__c = o.Id;
         p.Name = o.Name;
         p.OwnerId = '005b0000000hZc9';  
         if( o.Stage_One__c != Null){
             p.Stage_five_Invoice__c = 'Ready to Invoice';}//end if
        }//end if
      
        if (o.Job_Type__c == '2'  )
        {
        p.Project__c = o.Id;
  p.Name = o.Name;
        p.OwnerId = '005b0000000hIRM';
        if( o.Stage_One__c != Null){
             p.Stage_five_Invoice__c = 'Ready to Invoice';}//end if
        }//end if
      
         if (o.Job_Type__c == '3'  )
        {
   p.Project__c = o.Id;
         p.Name = o.Name;
         p.OwnerId = '005b0000000jCjP';
         if( o.Stage_One__c != Null){
             p.Stage_five_Invoice__c = 'Ready to Invoice';}//end if
        }//end if

      
        if(trigger.newMap.get(o.name) != trigger.OldMap.get(p.Project__c)){
         PMInsert.add(p);
         }

  }//end for

  insert PMInsert;
     }//end trigger
Best Answer chosen by Denis O'Leary
AshlekhAshlekh
Hi,

I went through the code and found below line

if(trigger.newMap.get(o.name) != trigger.OldMap.get(p.Project__c)){
         PMInsert.add(p);
 }
Here : trigger.newMap.get(o.name) --> Trigger.newMap contain id as a key and opportunity records as value, but in your case your are try to get this reocord by passing opportunity name, 

All Answers

AshlekhAshlekh
Hi,

I went through the code and found below line

if(trigger.newMap.get(o.name) != trigger.OldMap.get(p.Project__c)){
         PMInsert.add(p);
 }
Here : trigger.newMap.get(o.name) --> Trigger.newMap contain id as a key and opportunity records as value, but in your case your are try to get this reocord by passing opportunity name, 

This was selected as the best answer
Denis O'LearyDenis O'Leary
Ok, I got it now