Today, We are have created the post for explaining the below three topics.
- How to add custom error message in Apex Trigger
- How to query the related contact and checking the values
- How check the old map and new map values.
Scenario is : When we change the Account type, we have to check the related contacts and make to show the error, If the Primary Contact filed doesn’t marked true.
Coding Is Below:
Trigger AccountTrigger on Account (before Update,before insert) {
List<id> AccountIds = new List<id>();
boolean flag = false;
for(Account acc : Trigger.New){
Account oldAccount = Trigger.oldMap.get(acc.ID);
if(acc.type != oldAccount.type) {
AccountIds.add( acc.Id);
}
}if(AccountIds.size() > 0){
List <Contact> ContactList = new List<Contact> ();
ContactList = [select id, Primary_contact__c from contact where Contact.AccountId IN : AccountIds];for(Contact con: ContactList){
if (con.Primary_contact__c){
flag = true;
}
}if(!flag){
Trigger.New[0].addError(‘Please enable the Primary contact one’);
}}}
We are the ISV Partners and Please reach us for custom development => http://www.merfantz.com