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
shrayas reddyshrayas reddy 

custom error message not being displayed. I am getting error when required but the custom error message is not being displayed

trigger parentAccounttrigger on Account (before insert) {
parentAccount.parent(trigger.new);
   
}

--***--

public class parentAccount {
    public static void parent(List<account> acc){
        Set<Id> Ids = new Set<Id>();
        List<Account> acct = new List<Account>();
        for(account a:acc){
            if(a.ParentId != null){
           Ids.add(a.ParentId);
        }
        }
        acct = [SELECT Name, Id,ParentId FROM Account WHERE Id=:Ids]; 
        for(Account ac:acct){
            if(ac.ParentId != null){
// the below custom mssage is not being displayed
                ac.addError('There is already a parent for your parent account');
            }
        }
     
    }
}
CharuDuttCharuDutt
Hii Sharayas 
Try Below Code
trigger ParentTrigger on Account (before insert) {
 Set<Id> Ids = new Set<Id>();
        for(account a:trigger.new){
            if(a.ParentId != null){
           Ids.add(a.ParentId);
        }
        }
        List<Account> acct = [select id,name,(select id,Name from ChildAccounts) from account WHERE Id=:Ids]; 
        for(Account ac:trigger.new){
            if(acct.size()>0){
// the below custom mssage is not being displayed
                ac.addError('There is already a parent for your parent account');
            }
        }
     
}
Please Mark It As Best Answer If It Helps
Thank You! 
shrayas reddyshrayas reddy
Hi see my task is if a choosen parent account for a new Account already has a parent account then it shoud throw an error. The answer u gave will throw error when ever i choose any parent account irrespective of it has a parent record
CharuDuttCharuDutt
Hii Sharayas
Try Below Code
trigger ParentTrigger on Account (before insert) {
 Set<Id> Ids = new Set<Id>();
        for(account a:trigger.new){
            if(a.ParentId != null){
           Ids.add(a.ParentId);
        }
        }
        List<Account> acct = [select id,name from account WHERE Id=:Ids AND parentId != null]; 
        for(Account ac:trigger.new){
            if(acct.size()>0){
                ac.addError('There is already a parent for your parent account');
            }
        }
     
}
Please Close Your By Marking It As Best Answer If It Helps So It Also Helps Others In Future
Thank You!