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
vijay k 8vijay k 8 

regarding update on contacts

Hi All,
          this is the requirement,in every contact record  have one checkbox(boolean).for every account record only one primry contact will exist with  checkbox (checked).when ever a user wants to insert a new  record with checkbox checked   it will  show the user already exits the record with checkbox but it will allow any number of records with out check .the checkbox (unchecked). can any one help me on this.thanks in advance.

Dhanya NDhanya N
Hi Vijay,

Please check below trigger and class

trigger primaryContact on Contact (before insert) {

    parimaryContactHandler objHandler = new parimaryContactHandler();
    if(trigger.isBefore && trigger.isInsert)
public class parimaryContactHandler {

    public void onBeforeInsert(list<Contact> lstContact) {
        set<Id> setAccountId = new set<Id>();
        string strError = '';
        for(Contact objContact : lstContact) {
        for(Account objAccount : [Select Id, (Select Id, Primary__c From Contacts Where Primary__c = true limit 1) From Account Where Id IN: setAccountId]) {
            strError = 'There is already exists Primary record with this Account';         
        if(strError != '') {
            for(Contact objContact : lstContact) {               

Use following trigger. (change field names as per the correct Api names in your org)
(Correct typos & syntax errors if any)
trigger TriggerName on Contact(before insert)
	//replace booleanfieldName with correct field API name in the code
	if(Trigger.isBefore && Trigger.isInsert){
		List<Id> idList = new List<Id>(); //to store newly created contacts that have booleanFieldName set to TRUE
		for(Contact c:{
			if(c.booleanFieldName == true)
		// holds (Account.Id,Account Record) pairs for stored contacts that have booleanFieldName set to TRUE
		Map<Id,Account> acMap = new Map<Id,Account>([Select id, (Select id From Contacts Where booleanFieldName=true AND AccountId IN:idList) From Account]);
		// to add error message for those contacts whose parent Account already has primary contact, other contacts would sail through
			if(c.booleanFieldName==true && acMap.containsKey(c.AccountId))
				c.addError('Primary Contact Already Exists');

If this helps you out, please Mark it as Best Answer.