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
larvalarva 

apex class code with trigger

Account related to the updated Contact does not yet have a Primary Contact. I can create a lot of contact as long as there are no existing primary contact.
When an existing Non-Primary Contact is updated to become a Primary Contact
If the Account already has a Primary Contact it will display error. 
CharuDuttCharuDutt
Hii Larva
Try Below Trigger
trigger testTrigger on Contact ( before insert,before update) {
	set<Id> lstid = new set<Id>();
    If(trigger.IsBefore){
        if(Trigger.IsInsert){
            for(Contact Con :Trigger.new){
        	if(Con.Level__c == 'Primary'){
            lstid.add(Con.AccountId);
        		}
            }
        }
        If(Trigger.IsUpdate){
    		for(Contact Con :Trigger.new){
        	if(Con.Level__c == 'Primary' && Con.Level__c != Trigger.oldMap.get(Con.Id).Level__c){
            lstid.add(Con.AccountId);
        		}
        	}
    	}
    }
    
    list<Contact> lstCon = [Select id,AccountId,Level__c from Contact Where AccountId In : lstid AND level__c = 'Primary'];
    for(Contact Con : Trigger.new){
        if(lstCon.size()>0){
            con.AddError('Change level');
        }
    }
}
Please Mark It As Best Answer If It Helps
Thank You!