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
ChuckchoChuckcho 

trigger to check two fields to stop duplicates.

Hi All,

 

I wrote below trigger to check  two fields on opportunity to stop duplicates. I'm not sure what I'm missing but for some reason the code is not working as its supposed. Can someone assist me with this

 

trigger OpptyDupeCatcher on Opportunity (before insert, before update) {

 

Map<String, Opportunity> OpportunityMap = new Map<String, Opportunity>();
Map<String, Opportunity> AccountNameMap = new Map<String, Opportunity>();


for (Opportunity opportunity : System.Trigger.new) {

// Make sure we don't treat an name and account name that
// isn't changing during an update as a duplicate.
if ((opportunity.name != null && opportunity.account.name !=null) && (System.Trigger.isInsert || ((opportunity.name != System.Trigger.oldMap.get(opportunity.Id).name) &&
(opportunity.account.name != System.Trigger.oldMap.get(opportunity .Id).account.name)) )){
// Make sure another new Opportunity isn't also a duplicate
if ((OpportunityMap.containsKey(opportunity.name))&& (AccountNameMap.containsKey(opportunity.account.name))) {
opportunity.name.addError('Another new Opportunity in your business has the same name and account name. ID = ' + opportunity.Id);
} else {
OpportunityMap.put(opportunity.name, opportunity);

system.debug ( 'opportunitymap' + OpportunityMap.KeySet());

AccountNameMap.put(opportunity.account.name, opportunity);
system.debug ( 'opportunitymap' + accountNameMap.KeySet());

}
}
}

// Using a single database query, find all the Opportunities in
// the database that have the same name as any
// of the opportunities being inserted or updated.
for (Opportunity opportunity : [SELECT Name, Id, account.name from Opportunity WHERE Name IN : OpportunityMap.KeySet()
AND account.name IN: AccountNameMap.KeySet()])
{

system.debug ('opportunity name is' + opportunity.name);

Opportunity NewOpportunity = OpportunityMap.get(opportunity.name);


system.debug('Opportunity: ' + NewOpportunity);
NewOpportunity.Name.addError('An Opportunityt with this name and account name already exists for your business. Id = ' + opportunity.Id);
}

}

AmitSahuAmitSahu

Are you sure the code is going into the for loop you are using ?

PaqsPaqs

What do you mean by:

 

"but for some reason the code is not working as its supposed...."

 

What are you getting / not getting processed by the code.