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
Ching HoryChing Hory 

Trigger urgent help

I have custom picklist field with primary and secondary values in contact , for each account there must be one contact with primary selected and rest all  contacts will be secondary ..!!
how can i achieve this..

Thnks in advance  :)
Thnks community ..!!
SANDEEP CHITTINENISANDEEP CHITTINENI
Hi Ching,

I have developed trigger that helps you. please find it below
trigger contactPicklist on Contact(before insert){
    Map<ID,Contact> accountIds = new Map<ID,Contact>();
    for(Contact c : Trigger.New){
        accountIds.add(c.AccountId,c);
    }    
    for(Account acc : [Select Id, (Select Id, somecustomPicklistField from Contact) From Account Where Id IN accountIds.keyset()]){
        for(Contact con : acc.contacts){
            //Checking the picklist value, what user has selected
            if(accountIds.get(acc.Id).somecustomPicklistField == 'Primary'){
                //Checking the contacts already exists in the database
                //You can customize the below if and else conditions based on your requirements.
                if(con.somecustomPicklistField == 'Primary'){
                    con.addError('There is already one primary contact exists.');
                }
                else{
                    
                }
            }
            //Checking the picklist value what user has selected.
            else if(accountIds.get(acc.Id).somecustomPicklistField == 'Secondary'){
                //Checking the contacts already exists in the database.
                //You can customize the below if and else conditions based on your requirements.
                if(con.somecustomPicklistField != 'Primary'){
                    con.addError('There is no Primary Contact for this current');
                } 
                else{
                    
                }
            }
        }
    }
}

Let me know if you have any changes needed in the code. Please mark it as the best answer if this really helps you...
Ching HoryChing Hory
HI not clered .. getting so many errors there...!!
SANDEEP CHITTINENISANDEEP CHITTINENI
You need to replace "somecustomPicklistField" with your picklist field API name. And Can you post errors coming up if the error is not resolved?
Ching HoryChing Hory
User-added image