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
MEER ALIMEER ALI 

Apex Trigger not working

What is wrong with this trigger , it is not working . 
trigger RestrictContactByName on Contact (before insert,before update) {
  
List<Contact> cons = [Select Id from Contact where (Id IN :Trigger.New)];
    for (Contact c : cons)   {
        
        if(c.LastName == 'INVALIDNAME') 
             {
           
            c.AddError('The Last Name "'+c.LastName+'" is not acceptable');
              }

    }

    }

 
Amit GhadageAmit Ghadage
Hi MEER ALI,
This trigger will work for before update but not  for before insert as there is no id for record so cons List will be always empty for before insert trigger.
and Trigger.new itself is contact list so no need to query

modify your code to following.
 
trigger RestrictContactByName on Contact (before insert,before update) {
  
    for (Contact c : Trigger.New)   {
        
        if(c.LastName == 'INVALIDNAME') 
             {
           
            c.AddError('The Last Name "'+c.LastName+'" is not acceptable');
              }

    }

    }



Best Regards,
Amit Ghadage
Amit Chaudhary 8Amit Chaudhary 8
No need to To Query record. Please update your code like below
rigger RestrictContactByName on Contact (before insert, before update) {
    
    //check contacts prior to insert or update for invalid data
    For (Contact c : Trigger.New) {
        if(c.LastName == 'INVALIDNAME') {   //invalidname is invalid
            c.AddError('The Last Name "'+c.LastName+'" is not allowed for DML');
        }

    }



}
Please check below post for same issue
1) https://developer.salesforce.com/forums/?id=906F00000005GIKIA2

Let us know if this will help you