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
AkshiiiiiAkshiiiii 

trigger to prevent duplicates in a record

Requirement - I have a Student Object in which there is a Subject Field. I need to create a trigger that prevents duplication of Subject for each student. Eg- If Student 'A' has a Subject English then that Student should not be allowed to add English again. But at the same time, another Student 'B' can add English as a Subject (if not previously added for Student 'B'). 

How can I achieve this?
CharuDuttCharuDutt
Hii Akshii
Try Below Trigger
trigger PreventDuplicateContacts on Contact (before insert) {
    Set <String> subjectSet = new Set<String>(); 
    for (contact con:trigger.new) {
        subjectSet.add(con.Subject__c);
        
    }
    List <Contact> contactList = [SELECT Email,Subject__c FROM Contact WHERE Subject__c IN :subjectSet];

    for (contact con:trigger.new) {
        If (contactList.size() > 0) {
            
          con.Subject__c.adderror( 'Duplicate Contact Found. Use Existing Contact.' );
            
        }
    }
}
Please Mark It As Best Answer If It Helps
Thank You!
AkshiiiiiAkshiiiii
Hi CharuDutt,

Thank you for your response but this is not exactly what I am looking for.
 
CharuDuttCharuDutt
Hii Akshii
Try Below Trigger
trigger PreventDuplicateContacts on Contact (before update) {
    Set <String> subjectSet = new Set<String>(); 
    for (contact con:trigger.new) {
        subjectSet.add(con.Subject__c);
        
    }
    List <Contact> contactList = [SELECT Email,Subject__c FROM Contact WHERE Subject__c IN :subjectSet];

    for (contact con:trigger.new) {
        If (contactList.size() > 0) {
            
          con.Subject__c.adderror( 'Duplicate Contact Found. Use Existing Contact.' );
            
        }
    }
}
Please Mark It As Best Answer If It Helps
Thank You!