0

I need to write a trigger which allows only one primary account for opportunity. I am having a checkbox field in the account. so when i click that check box that account must be the primary account others not.

I don't know how to write the trigger for this?? can anyone help me to fix this??

6 Answers 6

3

Create a trigger on contact object on insert and update. Get the account I'd of the contact and store it in a variable to I'd type. Then get all the list of contacts and primary checkbox field for that account. Have a loop over all the contacts and see if any of the contacts is set as primary.

If there is already any such contact present then throw an exception . Else allow the contact to get inserted.

Hope this will provide you some idea on how to get started

Regards Ruchi

1

Try This:

trigger checkaccount on contact(before insert, before update){
    for(contact con : trigger.new){
        if(con.accountId != null){
            Id a = con.accountId;
            list<contact> cList = [SELECT Id, Check_box_name__c FROM Contact where Check_box_name__c = true and AccountId = :a];
            if(cList.size() > 0){
                con.addError('no more primary contacts');
            }
        }
    }
}

Update Above code, I got SOQL inside for loop, if you wish to avoid that... and also as per the suggestion in below comment:

trigger checkaccount on contact(before insert, before update){

    List<Id> accID = new List<Id>();
    for(contact c : trigger.new){
        if(c.accountId != null){
            accID.add(c.accountId);
        }
    }

    List<account> acc = [select id, (select id, Check_box_name__c from contacts where Check_box_name__c = true) from Account WHERE Id In: accID];
 Map<id, boolean> bool = new map<id,boolean>();
    for(account a : acc){
        bool.put(a.id, a.contacts.size()>0 ? true : false);
    }

    for(Contact c : trigger.new){
        if(bool.get(c.AccountId) == true){
            c.addError('no more primary fields');
        }
    }

}
1
  • Does not check boundary condition where a trigger.new contains two or more contacts for same account with Primary__c = true. While this might not happen from the UI it could happen in a batch load. Commented Sep 19, 2015 at 21:25
1

trigger onlyOnePrimaryKey on Contact (before insert, before update) {

//Step 1 :: collect accountId from trigger.new in a set . 
Set<Id> setAccId = new Set<Id>();
for(Contact con : trigger.new){
    if(String.isNotBlank(con.AccountId)){
       setAccId.add(con.AccountId);
    }
}

// STEP 2 :: Query All Accounts and related contacts using inner query .

List<Account> lstAcc = [select id , name,(select id,primaryContact__c from contacts where primaryContact__c = true limit 1)  from account where Id IN:setAccId];

 //STEP 3 :: Construct a map of acc Id and boolean value . 
Map<Id,Boolean> mapOfAccHavingPContact = new  Map<Id,Boolean>();

for(Account acc : lstAcc){
    if(acc.contacts.size() == 1){
        mapOfAccHavingPContact.put(acc.Id,true);
    }
}
for(Contact con : trigger.new){
    if(con.primaryContact__c && mapOfAccHavingPContact.containsKey(con.AccountId)){
        con.primaryContact__c.addError('Selected Account already have primary contact ');
    }
}

}

0

Thanks folks for your reply, got some idea and done a trigger hope It is right. if it is right give me your reply that would encourage me.

Set<Id> accountIds = new Set<Id>();
    Map<Id,Contact> PrimaryConforAcc = new Map<Id,Contact>();
    Map<Id,String> updatecon = new Map<Id,String>(); 
    List<Contact> oldContactlist = new List<Contact>();       
    if(trigger.IsInsert && trigger.IsBefore) 
    {

        for (Contact newcontact : trigger.new)
        {
            if(newContact.Primary__c == true)
            {            
                if(!PrimaryConforAcc.containsKey(newContact.AccountId))
                {            
                    accountIds.add(newcontact.AccountId);
                    PrimaryConforAcc.put(newcontact.AccountId,newContact);
                }
                else
                {
                    newContact.addError('Only one contact can be the primary. uncheck all other Primary custom field');
                }                
            }
        }
        if((accountIds !=NULL) && (accountIds.size()>0))
        {
            for (Contact primaryContact : [SELECT Name,Primary__c,AccountId FROM Contact WHERE AccountId IN :accountIds])
            {
               if(primaryContact.Primary__c==true)
               {                                     
                    primaryContact.addError('only one primary contact is possible and already present here');                                                                   
               } 

            }
        }                    
    }
1
  • Code needs to check both before insert and before update. It is currently only checking inserts. The SELECT ..FROM contact should filter on Primary__c == true. There is no need to check every contact that has Primary__c set to False Commented Sep 19, 2015 at 21:21
0

Hope this would works. its working for me now.


trigger ContactMap on Contact (before Insert,After Update){ Set accountIdSet = new Set(); Set contactIdSet = new Set(); Map> accIdAndContactListMap = new Map>(); Map accIdAndContactCountMap = new Map();
List oldContactList = new list(); Integer Count =0;
if(trigger.IsInsert && trigger.IsBefore){

    for (Contact newcontact : trigger.new){

        if(newContact.Primary__c == true && newcontact.AccountId!=NULL ){

            if(!accountIdSet.Contains(newContact.AccountId)){            
                accountIdSet.add(newcontact.AccountId);                    
            }else{                   
                newContact.addError('Only one contact can be the primary.Must Not Add all contacts as primary contact');
            }                
        }
    }    

    if((accountIdSet !=NULL) && (accountIdSet.size()>0)){        
        OldContactList=    [SELECT Name,Primary__c,AccountId 
                            FROM Contact 
                            WHERE AccountId IN :accountIdSet AND Primary__c=TRUE];                                              

        for(Contact cnt : OldContactList){                                                 
            accIdAndContactCountMap.put(cnt.AccountId,1);                                                                                                                                                                      
        }
        system.debug('::::++++++'+accIdAndContactCountMap);                       
        for(Contact newcontact : trigger.new){

            if(newcontact.AccountId!=NULL && accIdAndContactCountMap.containsKey(newcontact.AccountId)){
            Count = accIdAndContactCountMap.get(newcontact.AccountId);
            if(Count==1){
                system.debug('+++++count------'+Count);                        
                newcontact.addError('One primary contact is already Available,Inserting another primary contact is not Possible.');
            }
            } 
        }
    }        
}

if(trigger.IsUpdate && trigger.IsAfter){
    for(Contact newupContact : Trigger.new){// validation for a particular contact whether it is already primary or not.

        if(newupContact.Primary__c == true && newupContact.AccountId!=NULL &&
         (Trigger.oldmap.get(newupContact.Id).Primary__c == FALSE || 
            Trigger.oldmap.get(newupContact.Id).Primary__c == TRUE )){ //unchecked primary, to check the new value

                if(!accountIdSet.Contains(newupContact.AccountId)){
                    accountIdSet.add(newupContact.AccountId);//primary checkbox newly checked value Id will be here.                                                                                                              
                    system.debug('++++++++'+accountIdSet);
                    contactIdSet.add(newupContact.Id);
                }else if(accountIdSet.Contains(newupContact.AccountId)){//If two contacts of same id is not allowed                
                    newupContact.addError('When updating or inserting, Only 1 contact can be the primary. uncheck all other Primary custom field');
                }
        }                                              
    }   
    if((accountIdSet !=NULL) && (accountIdSet.size()>0))
    {    
        OldContactList=    [SELECT Id,Name,Primary__c,AccountId 
                            FROM Contact 
                            WHERE AccountId IN :accountIdSet AND Primary__c=TRUE AND Id NOT IN :contactIdSet];               
        //system.debug('********'+OldContactList[0].AccountId);
        for(Contact cnt : OldContactList){                                
            accIdAndContactCountMap.put(cnt.AccountId,1);  
            system.debug('********'+accIdAndContactCountMap);
        }
        for(Contact newcontact : trigger.new){

            if(newcontact.AccountId!=NULL && accIdAndContactCountMap.containsKey(newcontact.AccountId)){
            Count = accIdAndContactCountMap.get(newcontact.AccountId);                                
                if((Count==1)&&(newcontact.Primary__c==TRUE)){
                  system.debug('+*-+*-+*-+*+-'+Count);  
                  newcontact.addError('update is not Possible. one primary contact is allowed for a Account and it is already Available');
                }
            }

        }            
    }        
}

}

-2
trigger PrimaryContactTrigger on Contact (before insert,before update) {
    set<id> accid= new Set<Id>();
        if(trigger.isinsert || trigger.isupdate){   
          for(Contact c:trigger.new){
            if(c.Accountid!=null && c.Primary_Contacts__c==true){
                accid.add(c.accountid);
            }
        }   
    }
    List<Contact> conList = [Select id,name,Primary_Contacts__c from Contact where Primary_Contacts__c=true and Accountid in:accid];
        if(conList.size()>0) {
        for(Contact c:Trigger.new){
        c.adderror('No more Primary Contacts');
        }
    }
}

Not the answer you're looking for? Browse other questions tagged .