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
louisa barrett 7louisa barrett 7 

Apex trigger to create two custom objects on Opportunity

Hi,
Can anyone offer some assistance with this scenario please.
I have a trigger that should be creating one of each custom object(Project_sheet__c and Project_checklist__c) when the opportunity is saved.
Both custom objects have Opporutnity look ups. The trigger was sort of working, but unfortunately I was getting multiple records being created.
I do have workflows on the Opportunity that fire when the opportunity is saved, as well as an additional trigger that creates an asset for each OLI.
I thought the issue was as this trigger is an 'Update' as well as an 'Insert', it was causing it to re-fire.
I've attempted to add a conditional statement that if there is already a Project checklist or Project sheet associated with the Opportunity then it shouldn't create an additional record.
Unfortunately it's not working at all now.
I've highlighted the additional conditional statement in bold that appears to have stopped the trigger working at all.
Any help would be appreciated.

Current trigger:

trigger InsertProjectDocuments on Opportunity (after insert, after update) {
List<Project_sheet_2__C> projSheetToInsert = new List<Project_sheet_2__C>();
List<Project_checklist__c> projChecklistToInsert = new List <Project_checklist__c>();
   
    for(Opportunity opp : Trigger.new) {
        if (opp.IsWon && (opp.Project_sheets_21__r != null) && (opp.project_sheets_21__r != Trigger.oldMap.get(opp.id).Project_sheets_21__r) && (Trigger.oldMap.get(opp.Id).IsWon !=opp.IsWon)) {
            Project_sheet_2__c ps = new Project_sheet_2__c();
            ps.Name = 'Project sheet -' + opp.name;
            ps.PS2_Opportunity__c = opp.id;
            ps.Date_created__c = system.today();  
            ps.Version_Number__c = '1';
            projSheetToInsert.add(ps);            
        }
        if (opp.IsWon && (opp.Project_sheets_2__r != null) && (opp.project_sheets_2__r != Trigger.oldMap.get(opp.id).Project_sheets_2__r) && (Trigger.oldMap.get(opp.Id).IsWon !=opp.IsWon)) {
            Project_checklist__c pc = new Project_checklist__c();
            pc.Name = 'Checklist -' + opp.Name;
            pc.Project_opportunity__c = opp.id;
            projChecklistToInsert.add(pc);
        }
    }
    if(projSheetToInsert.size() >0){
        Database.insert(projSheetToInsert, false);
    }
    if(projChecklistToInsert.size() >0){
    Database.insert(projChecklistToInsert, false);
    }
}
 
Best Answer chosen by louisa barrett 7
ManojjenaManojjena

Hi Louisa,
try with below code it will help !!
 
trigger InsertProjectDocuments on Opportunity (after update) {
    List<Project_sheet_2__C> projSheetToInsert = new List<Project_sheet_2__C>();
	List<Project_checklist__c> projChecklistToInsert = new List <Project_checklist__c>();
    Map<Id,Opportunity> oppMap=new Map<Id,Opportunity>();
	List<Opportunity> oppList;
    for(Opportunity opp : Trigger.new) {
		if(opp.StageName=='Closed/Won' && Trigger.oldMap.get(opp.Id).StageName != opp.StageName){
		   oppMap.put(opp.Id,opp);
		}
    }
	if(!oppMap.isEmpty()){
	   for(Opportunity opp :[SELECT id,Name,(SELECT id,Name,PS2_Opportunity__c FROM Project_sheets_21__r),(SELECT Id,Name,Project_opportunity__c FROM project_sheets_2__r) FROM Opportunity WHERE Id IN : oppMap.keySet()]){
	     oppIdWithChkLstMap.put(opp.Id,opp.Project_sheets_21__r.size()); 
		 oppIdWithSheetMap.put(opp.Id,opp.project_sheets_2__r.size());
         if(opp.Project_sheets_21__r.size()){
		    Project_checklist__c pc = new Project_checklist__c();
				pc.Name = 'Checklist -' + oppMap.get(opId).name;
				pc.Project_opportunity__c = opId;
				projChecklistToInsert.add(pc);
		 }if(opp.project_sheets_2__r.size()==0){
		    Project_sheet_2__c ps = new Project_sheet_2__c();
				ps.Name = 'Project sheet -' + oppMap.get(oppId).name;
				ps.PS2_Opportunity__c = oppId;
				ps.Date_created__c = system.today();  
				ps.Version_Number__c = '1';
				projSheetToInsert.add(ps);
         }
	   }
	}
	if(projSheetToInsert.size() >0){
	    try{
		   Insert projSheetToInsert;
		}catch(DmlException de ){
		   System.debug(de);
		}
	}
	if(projChecklistToInsert.size() >0){
	try{
		   Insert projChecklistToInsert;
		}catch(DmlException de ){
		   System.debug(de);
		}
	}
}

Check the relationship name in query try to modify incase any issue ,

Let me know if it helps !!
Thanks 
Manoj

All Answers

mritzimritzi
All you need to do is to separate logic for insert & update.
trigger InsertProjectDocuments on Opportunity (after insert, after update) {
	List<Project_sheet_2__C> projSheetToInsert = new List<Project_sheet_2__C>();
	List<Project_checklist__c> projChecklistToInsert = new List <Project_checklist__c>();
	
	if(Trigger.isAfter && Trigger.isInsert){
		for(Opportunity op:Trigger.new){
			//create new records on Project Sheet & Project CheckList objects
			// add them to repective list and insert
		}
		//insert Lists
	}
	else if(Trigger.isAfter && Trigger.isUpdate){
		for(Opportunity op:Trigger.new){
			//implement your logic that will work when opportunity will be updated
		}
	}
}

If this helps you out, mark this as Best Answer
cloudSavvyProgcloudSavvyProg
Hi Loiusa,

First thing is Trigger.oldMap is not available for Insert(before and after). So please remove that condition for Insert and move to update.

Second thing is your code is saying opp.Project_sheets_21__r != null then create records. Instead I think it should say opp.Project_sheets_21__c == null then create new record. Assuming Project_sheets_21__c is lookup field reference on Opp.

So your code will be as follows:

trigger InsertProjectDocuments on Opportunity (after insert, after update) {
List<Project_sheet_2__C> projSheetToInsert = new List<Project_sheet_2__C>();
List<Project_checklist__c> projChecklistToInsert = new List <Project_checklist__c>();
   
if(Trigger.isAfter)
{
if(Trigger.isInsert)
{
for(Opportunity opp : Trigger.new) {
        if (opp.IsWon && (opp.Project_sheets_21__r == null)) {
            Project_sheet_2__c ps = new Project_sheet_2__c();
            ps.Name = 'Project sheet -' + opp.name;
            ps.PS2_Opportunity__c = opp.id;
            ps.Date_created__c = system.today();  
            ps.Version_Number__c = '1';
            projSheetToInsert.add(ps);            
        }
        if (opp.IsWon && (opp.Project_sheets_2__r != null)) {
             Project_checklist__c pc = new Project_checklist__c();
            pc.Name = 'Checklist -' + opp.Name;
            pc.Project_opportunity__c = opp.id;
            projChecklistToInsert.add(pc);
        }
    }
}

if(Trigger.isUpdate)
{
for(Opportunity opp : Trigger.new) {
if (opp.IsWon && (opp.project_sheets_21__r != Trigger.oldMap.get(opp.id).Project_sheets_21__r)) {
//create the record
}

if (opp.IsWon  && (opp.project_sheets_2__r != Trigger.oldMap.get(opp.id).Project_sheets_2__r)) {
//create the record
}
}


}

        if(projSheetToInsert.size() >0){
        Database.insert(projSheetToInsert, false);
    }
    if(projChecklistToInsert.size() >0){
    Database.insert(projChecklistToInsert, false);
    }
}


I have just written in text pad. So it might not compile. But logic seems like what you are looking for.
 
Hope this helps.

Regards,
CloudSavvyProg
louisa barrett 7louisa barrett 7
Hi, 
Thanks for the advice.
The trigger still isn't firing, I've added some logging to try and pin point why.
I've also adjusted the update conditional statement, as I wasn't sure if that was the problem.

the trigger is now:

trigger InsertProjectDocuments on Opportunity (after insert, after update) {
List<Project_sheet_2__C> projSheetToInsert = new List<Project_sheet_2__C>();
List<Project_checklist__c> projChecklistToInsert = new List <Project_checklist__c>();
   system.debug('start');
    If(Trigger.isafter)
    {
        system.debug('Is after');
        if(Trigger.isInsert)
            system.debug('Is insert');
        {
           for(Opportunity opp : Trigger.new) {
               if (opp.IsWon && (opp.Project_sheets_21__r == null)) {
            Project_sheet_2__c ps = new Project_sheet_2__c();
            ps.Name = 'Project sheet -' + opp.name;
            ps.PS2_Opportunity__c = opp.id;
            ps.Date_created__c = system.today();  
            ps.Version_Number__c = '1';
            projSheetToInsert.add(ps);            
        }
        if (opp.IsWon && (opp.Project_sheets_2__r == null) ) {
            Project_checklist__c pc = new Project_checklist__c();
            pc.Name = 'Checklist -' + opp.Name;
            pc.Project_opportunity__c = opp.id;
            projChecklistToInsert.add(pc);
        }
             
        }
        
        }
        if(trigger.isUpdate)
            system.debug('Is update');
        {
                for(Opportunity opp : Trigger.new) {
                    system.debug(opp.iswon);
                    if (opp.IsWon && (opp.Project_sheets_21__r == null)) {
                     Project_sheet_2__c ps = new Project_sheet_2__c();
                    ps.Name = 'Project sheet -' + opp.name;
                    ps.PS2_Opportunity__c = opp.id;
                    ps.Date_created__c = system.today();  
                    ps.Version_Number__c = '1';
                    projSheetToInsert.add(ps);  
                        system.debug(ps.name);
            }
                    if(opp.IsWon && (opp.Project_sheets_2__r == null)){
                        Project_checklist__c pc = new Project_checklist__c();
                        pc.Name = 'Checklist -' + opp.Name;
                        pc.Project_opportunity__c = opp.id;
                        projChecklistToInsert.add(pc);
                        system.debug('pc.name');
                    }
        }
    }
    system.Debug('after if statement');
        system.debug(projSheetToInsert.size());
        system.debug(projChecklistToInsert.size());
    if(projSheetToInsert.size() >0){
        Database.insert(projSheetToInsert, false);
        system.debug('ps inserted');
    }
    if(projChecklistToInsert.size() >0){
    Database.insert(projChecklistToInsert, false);
        system.debug('pc inserted');
    }
    }
    system.debug('completed');
}


This is the logging I'm getting

User-added image

So as the Opp is marked as won it must be the remaining conditional statement.
I got the same result with the code that you gave me

if (opp.IsWon && (opp.project_sheets_21__r != Trigger.oldMap.get(opp.id).Project_sheets_21__r)) and 
if (opp.IsWon  && (opp.project_sheets_2__r != Trigger.oldMap.get(opp.id).Project_sheets_2__r))

Project_sheets_21__r and Project_sheets_2__r are the child realtionship names on the Opportunity Looup object on the respective custom object.

Many thanks
 
ManojjenaManojjena
Hi Loisa,
Try with below code it will help !!
trigger InsertProjectDocuments on Opportunity (after insert, after update) {
	List<Project_sheet_2__C> projSheetToInsert = new List<Project_sheet_2__C>();
	List<Project_checklist__c> projChecklistToInsert = new List <Project_checklist__c>();
	List<Project_sheet_2__C> projSheetToUpdate = new List<Project_sheet_2__C>();
	List<Project_checklist__c> projChecklistToUpdate = new List <Project_checklist__c>();
    if(trigger.isInsert){
	    Project_sheet_2__c ps = new Project_sheet_2__c();
		Project_checklist__c pc = new Project_checklist__c();
		 for(Opportunity opp : Trigger.new) {
			ps.Name = 'Project sheet -' + opp.name;
			ps.PS2_Opportunity__c = opp.id;
			ps.Date_created__c = system.today();  
			ps.Version_Number__c = '1';
			projSheetToInsert.add(ps);            
			pc.Name = 'Checklist -' + opp.Name;
			pc.Project_opportunity__c = opp.id;
			projChecklistToInsert.add(pc);
		}
    }if(trigger.isUpdate){
	   for(Opportunity opp : Trigger.new) {
	       Map<Id,Opportunity> projectChklstWithOppMap=new Map<Id,Opportunity>();
		    Map<Id,Opportunity> projectSheetWithOppMap=new Map<Id,Opportunity>();
	       if (opp.IsWon && Trigger.oldMap.get(opp.Id).IsWon ==false && opp.Project_sheets_21__r != null && opp.project_sheets_21__r != Trigger.oldMap.get(opp.id).Project_sheets_21__r ) {
		     projectChklstWithOppMap.put(opp.Project_sheets_21__r,opp);
		   
		   }
		   if (opp.IsWon && Trigger.oldMap.get(opp.Id).IsWon==false && opp.Project_sheets_2__r != null && opp.project_sheets_2__r != Trigger.oldMap.get(opp.id).Project_sheets_2__r) {
		      projectSheetWithOppMap.put(opp.project_sheets_2__r ,opp);
		   }
	   }
	}
	if(!projectChklstWithOppMap.isEmpty()){
	   for(Id  prjchkId : projectChklstWithOppMap.keySet() ){
	      Project_checklist__c prjchk=new Project_checklist__c(id=prjchkId,Name = 'Checklist -' + projectChklstWithOppMap.get(prjchkId).Name,Project_opportunity__c = projectChklstWithOppMap.get(prjchkId).id);
		  projChecklistToUpdate.add(prjchk);
	   }
	}
	if(!projectSheetWithOppMap.isEmpty()){
	   for(Id prjShtId :projectSheetWithOppMap.keySet() ){
	        Project_sheet_2__C prjsht=new Project_sheet_2__C(id=prjShtId,Name = 'Checklist -' + projectSheetWithOppMap.get(prjShtId).Name,PS2_Opportunity__c = projectSheetWithOppMap.get(prjShtId).id);
			projSheetToUpdate.add(prjsht);
	   }
	}
    if(projSheetToInsert.size() >0){
        Database.insert(projSheetToInsert, false);
    }
    if(projChecklistToInsert.size() >0){
        Database.insert(projChecklistToInsert, false);
    }
	if(!projChecklistToUpdate.isEmpty()){
	   update projChecklistToUpdate;
	}
	if(!projSheetToUpdate.isEmpty()){
	  update projSheetToUpdate;
	}
}

Let us kno wif it helps !!
Any typo mistake please correct from your end .
Thanks 
Manoj
louisa barrett 7louisa barrett 7
Hi, thanks for advice.

I'm getting a compile error of ' incompatible key type list for map' on the following lines
projectChklstWithOppMap.put(opp.Project_sheets_21__r,opp);
projectSheetWithOppMap.put(opp.project_sheets_2__r ,opp);
ManojjenaManojjena
Basically I have modified based on your code .

you need to write trigger in Opportunity which will create record on insert .

below code will help you .
 
trigger InsertProjectDocuments on Opportunity (after insert, after update) {
	List<Project_sheet_2__C> projSheetToInsert = new List<Project_sheet_2__C>();
	List<Project_checklist__c> projChecklistToInsert = new List <Project_checklist__c>();
	List<Project_sheet_2__C> projSheetToUpdate = new List<Project_sheet_2__C>();
	List<Project_checklist__c> projChecklistToUpdate = new List <Project_checklist__c>();
    if(trigger.isInsert){
	    Project_sheet_2__c ps = new Project_sheet_2__c();
		Project_checklist__c pc = new Project_checklist__c();
		 for(Opportunity opp : Trigger.new) {
			ps.Name = 'Project sheet -' + opp.name;
			ps.PS2_Opportunity__c = opp.id;
			ps.Date_created__c = system.today();  
			ps.Version_Number__c = '1';
			projSheetToInsert.add(ps);            
			pc.Name = 'Checklist -' + opp.Name;
			pc.Project_opportunity__c = opp.id;
			projChecklistToInsert.add(pc);
		}
    }
    if(projSheetToInsert.size() >0){
        Database.insert(projSheetToInsert, false);
    }
    if(projChecklistToInsert.size() >0){
        Database.insert(projChecklistToInsert, false);
    }
}

What exactly your update funcationality ? when you want to update record and what you want to update if you will explain bit more ,so that I wil help you to solve the issue .

Thanks 
Manoj
louisa barrett 7louisa barrett 7
Hi,

Basically, when an opportunity is marked as closed/won, if there are no instances of Project_checklist__c or Project_sheet_2__c associated to the Opportunity then the trigger should fire and one or both of the custom objects should get created. If the opportunity is re-saved when IsWon=True, the custom objects should not be re-created, unless no instances of teh custom objects exist.
If there is already an instance of the custom objects when the opportunity is marked as closed/won then the objects should not be created.

Hope this helps

 
louisa barrett 7louisa barrett 7
I've got it working, or a tleast it looks that way.
It's very messy though.
If you could offer some insight on how it could be tidied up, that would be great

trigger InsertProjectDocuments on Opportunity (after insert, after update) {
List<Project_sheet_2__C> projSheetToInsert = new List<Project_sheet_2__C>();
List<Project_checklist__c> projChecklistToInsert = new List <Project_checklist__c>();
List<Project_checklist__c> currentChecklists = new List <Project_checklist__c>();
List<Project_sheet_2__C> currentSheets = new List<Project_sheet_2__C>();

   system.debug('start');
    If(Trigger.isafter)
    {
        system.debug('Is after');
        if(Trigger.isInsert)
            system.debug('Is insert');
        {
           for(Opportunity opp : Trigger.new) {
               if (opp.IsWon && (opp.Project_sheets_21__r == null)) {
            Project_sheet_2__c ps = new Project_sheet_2__c();
            ps.Name = 'Project sheet -' + opp.name;
            ps.PS2_Opportunity__c = opp.id;
            ps.Date_created__c = system.today();  
            ps.Version_Number__c = '1';
            projSheetToInsert.add(ps);            
        }
        if (opp.IsWon && (opp.Project_sheets_2__r == null) ) {
            Project_checklist__c pc = new Project_checklist__c();
            pc.Name = 'Checklist -' + opp.Name;
            pc.Project_opportunity__c = opp.id;
            projChecklistToInsert.add(pc);
        }
             
        }
        
        }
        if(trigger.isUpdate)
            system.debug('Is update');
        {
                for(Opportunity opp : Trigger.new) {
                    system.debug(opp.iswon);
                    currentSheets = [select name from Project_sheet_2__c where PS2_Opportunity__c = :opp.id ];
                    if (opp.IsWon && currentSheets.size() ==0) {
                     Project_sheet_2__c ps = new Project_sheet_2__c();
                    ps.Name = 'Project sheet -' + opp.name;
                    ps.PS2_Opportunity__c = opp.id;
                    ps.Date_created__c = system.today();  
                    ps.Version_Number__c = '1';
                    projSheetToInsert.add(ps);  
                        system.debug(ps.name);
            }
                    currentChecklists = [select name from Project_checklist__c where Project_Opportunity__c = :opp.id ];
                    if(opp.IsWon && currentChecklists.size() ==0){
                        Project_checklist__c pc = new Project_checklist__c();
                        pc.Name = 'Checklist -' + opp.Name;
                        pc.Project_opportunity__c = opp.id;
                        projChecklistToInsert.add(pc);
                        system.debug('pc.name');
                    }
        }
    }
    system.Debug('after if statement');
        system.debug(projSheetToInsert.size());
        system.debug(projChecklistToInsert.size());
    if(projSheetToInsert.size() >0){
        Database.insert(projSheetToInsert, false);
        system.debug('ps inserted');
    }
    if(projChecklistToInsert.size() >0){
    Database.insert(projChecklistToInsert, false);
        system.debug('pc inserted');
    }
    }
    system.debug('completed');
}
ManojjenaManojjena

Hi Louisa,
try with below code it will help !!
 
trigger InsertProjectDocuments on Opportunity (after update) {
    List<Project_sheet_2__C> projSheetToInsert = new List<Project_sheet_2__C>();
	List<Project_checklist__c> projChecklistToInsert = new List <Project_checklist__c>();
    Map<Id,Opportunity> oppMap=new Map<Id,Opportunity>();
	List<Opportunity> oppList;
    for(Opportunity opp : Trigger.new) {
		if(opp.StageName=='Closed/Won' && Trigger.oldMap.get(opp.Id).StageName != opp.StageName){
		   oppMap.put(opp.Id,opp);
		}
    }
	if(!oppMap.isEmpty()){
	   for(Opportunity opp :[SELECT id,Name,(SELECT id,Name,PS2_Opportunity__c FROM Project_sheets_21__r),(SELECT Id,Name,Project_opportunity__c FROM project_sheets_2__r) FROM Opportunity WHERE Id IN : oppMap.keySet()]){
	     oppIdWithChkLstMap.put(opp.Id,opp.Project_sheets_21__r.size()); 
		 oppIdWithSheetMap.put(opp.Id,opp.project_sheets_2__r.size());
         if(opp.Project_sheets_21__r.size()){
		    Project_checklist__c pc = new Project_checklist__c();
				pc.Name = 'Checklist -' + oppMap.get(opId).name;
				pc.Project_opportunity__c = opId;
				projChecklistToInsert.add(pc);
		 }if(opp.project_sheets_2__r.size()==0){
		    Project_sheet_2__c ps = new Project_sheet_2__c();
				ps.Name = 'Project sheet -' + oppMap.get(oppId).name;
				ps.PS2_Opportunity__c = oppId;
				ps.Date_created__c = system.today();  
				ps.Version_Number__c = '1';
				projSheetToInsert.add(ps);
         }
	   }
	}
	if(projSheetToInsert.size() >0){
	    try{
		   Insert projSheetToInsert;
		}catch(DmlException de ){
		   System.debug(de);
		}
	}
	if(projChecklistToInsert.size() >0){
	try{
		   Insert projChecklistToInsert;
		}catch(DmlException de ){
		   System.debug(de);
		}
	}
}

Check the relationship name in query try to modify incase any issue ,

Let me know if it helps !!
Thanks 
Manoj
This was selected as the best answer