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
Kunal Purohit 4Kunal Purohit 4 

How to write trigger to given scenario?

Hello All, I am having two objects Account and Opportunity. Now scenario is that, there should be no duplicate entry of Account and Opportunity when i select stage field of opportuntiy. 
How to write trigger?
AnudeepAnudeep (Salesforce Developers) 
Hi Kunal, 

You can look at the following code as an example and make changes as per your needs
 
trigger AccountDuplicateTrigger on Account (before insert,before update) {

     //You may need to filter this a bit more if you have a very large number of accounts    
     map<Id,Account> existingAccountMap = new  map<Id,Account>([Select Id, Name, Rating From Account Where Rating != null]); 

     for(Account a : Trigger.new){
        //Remember to use Double equal
        if(a.name == existingAccountMap.get(a.Id).Name && a.rating == existingAccountMap.get(a.Id).rating){
          a.adderror('You cannot create a dulplicate account');
        }
     }
}

let me know if it helps

Anudeep
 
Andrew GAndrew G
Ignore trigger - go Duplication Rules in Setup.   But i guess that's only if this is real life and not some coding exercise.