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
cFangcFang 

Prevent Duplicate Records

The code below is setup to automatically create projects for all opportunities that reach a probability of >=90%. I am new to APEX coding and would like to add additional statements that would only allow 1 project for each opportunity. Right now, if an opportunity is updated from 90% to 100% an additional project would be created. What is the best way to limit the code so that only 1 project is created for each opportunity regardless of how many times the probability is updated?

 

Any help is greatly appreciated.

 

This is the code:

 

trigger Locate_Prob90_Opportunities on Opportunity (after update,after insert) {
	
	list<Opportunity> p90opps =
	[select probability
	from opportunity
	where probability >=90
	for update];
	
	for (opportunity oppz: p90opps){
		if(oppz.probability>=90){
			SFDC_project__c prject = new SFDC_Project__c(name='Acme test',opportunity__c=oppz.id);
	
			insert prject;
		
		}
	}
	
	
}

 

 

Best Answer chosen by Admin (Salesforce Developers) 
Jake GmerekJake Gmerek

Actually, it may be easiest to do this with a validation rule, all you do is add a custom field to the project object with a formula of one, so it is a constant of 1.  Then you add a roll-up field on the opportunity that sums that field.  Finally a validation rule on the project object that fires if the roll-up field is >= 1.  The only downside is that you would have to check and see if the update on the opprotunity is rolled back when the insert fails, i think that it might, but I am not sure.

 

If you wanted to do it in apex you would do something like:

 

List<ID>oppIds = new List<ID>();

for (opportunity o: p90opps){oppIds.add(o.id);}

 

List <SFDC_project__c> pList = new List<SFDC_project__c>([select id from SFDC_project__c where opportunity__c IN: oppIds]);

 

if (pList.isempty()){

 

...do work

 

 

}