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
snehil kumarsnehil kumar 

Please help me to write the trigger for my requirements.

Hi All,

I have posted my requirements, please help me to write the trigger Thanks in Advance.

Create a field in Account => NumOfContact__c
This field should be a pick list. Values - 1,2,3,4,5

This field value should be same as the number of contacts in the related list.

snehil kumarsnehil kumar

Thanks for your response,I have also done the same things.but the requirements is different.

Explanation of requirements: There is a picklict field on Account, when we select the value from picklist. it allows us to create the same number of record on contact side.

Suraj Tripathi 47Suraj Tripathi 47
Hi snehil kumar,
Greeting!

Custom Field should be number type, not a Piclist because it takes an integer value of account child means NumOfContact__c value.

You can use this Code:
trigger triggerOnContactNEW1 on Contact (after insert) {
    
    list<contact> conList = [select id,lastName,accountId from contact where accountId !=null and id in:trigger.new limit 1000];
    set<id> setAccIdCon =new set<id>(); 
    for(contact con:conList){
        setAccIdCon.add(con.accountId);
    }
    system.debug(setAccIdCon);    
    list<AggregateResult> aggList = [select accountId conAccId, Count(id) TotalCon from contact where accountId in:setAccIdCon Group By accountId ]; 
     list<account> accList = new list<account>();              
    for(AggregateResult agg:aggList){ 
        Account acc = new Account();
        acc.Id = (Id) agg.get('conAccId'); 
        acc.NumOfContact__c = (Integer) agg.get('TotalCon'); 
        accList.add(acc); 
    update accList; 
    

}
If you find your Solution then mark this as the best answer. 

Thank you!

Regards 
Suraj Tripathi
CharuDuttCharuDutt
Hii Snehil
Try Below Code
trigger test on Account (After Insert ,Before Update) {
    id acId;
    integer o ;
    list<Contact> lstCon = new list<Contact>();
    if((Trigger.IsAfter && Trigger.IsInsert) || (Trigger.IsAfter && Trigger.IsInsert)){
        for(Account Acc:trigger.new){
            acId=Acc.Id;
            o= Integer.valueOf(Acc.NumOfContact__c);
        }
    }
    for(integer i=0;i<o;i++){
        Contact Con = new Contact();
        Con.FirstName ='Test';
        Con.LastName = string.valueOf(i);
        Con.AccountId = acId;
        lstCon.add(Con);
    }
    insert lstCon;

}
Please Mark It As Best Answer If It Helps
Thank You!
 
snehil kumarsnehil kumar
Thanks for response. One more scenario if there is already 5 contact related to the account. But after that we have selected pick list filed value as 2. Then it should delete the other 3 keeping only 2 contact.
Suraj Tripathi 47Suraj Tripathi 47
Hi snehil,
You can take reference from this below code:-
trigger accountTrigger on Account (after insert,before update) {
    if(Trigger.IsAfter && Trigger.IsInsert){
        list<contact> connList= new list<contact>();
        for(account acc: trigger.new){
            for(integer i=0;i<acc.NumOfContact__c;i++){
                contact con= new contact();
                con.LastName='test';
                con.AccountId=acc.Id;
                connList.add(con);
            }
        }
        insert connList;
    }
    if(Trigger.IsBefore && Trigger.IsUpdate){
        map<id,account> accList=new map<id,account>([select id,NumOfContact__c,(select accountid,Lastname,id from contacts) from account where id IN: trigger.old]);
        system.debug('abcc');
        map<id,integer> insertCountContactMap= new map<id,integer>();
        map<id,integer> deleteCountContactMap= new map<id,integer>();
        map<id,List<contact>> deleteContactMap= new map<id,List<contact>>();
        
        for(account oldAcc:trigger.old){
            for(account newAcc:trigger.new){
                if(oldAcc.id==newAcc.id && oldAcc.NumOfContact__c!=newAcc.NumOfContact__c){
                    system.debug(oldAcc.NumOfContact__c+' '+newAcc.NumOfContact__c);
                    if(oldAcc.NumOfContact__c<newAcc.NumOfContact__c){
                        integer diff=newAcc.NumOfContact__c-accList.get(oldAcc.id).contacts.size();
                        if(diff>0){
                            insertCountContactMap.put(oldAcc.id,diff);
                        }
                        else{
                            deleteCountContactMap.put(oldAcc.id,-diff);
                            deleteContactMap.put(oldAcc.id,accList.get(oldAcc.id).contacts);
                        }
                    }
                    else{
                        integer diff=accList.get(oldAcc.id).contacts.size()-newAcc.NumOfContact__c;
                        if(diff>0){
                            deleteCountContactMap.put(oldAcc.id,diff);
                            deleteContactMap.put(oldAcc.id,accList.get(oldAcc.id).contacts);
                        }
                        else{
                            insertCountContactMap.put(oldAcc.id,-diff);
                        }
                    }
                }
            }
        }
        system.debug(insertCountContactMap);
        system.debug(deleteContactMap);
        List<contact> insertContact= new List<contact>();
        for(id id1:insertCountContactMap.keyset()){
            for(integer i=0;i<insertCountContactMap.get(id1);i++){
                contact con= new contact();
                con.Lastname='test '+i;
                con.AccountId=id1;
                insertContact.add(con);
            }
        }
        if(insertContact.size()>0){
            insert insertContact;
        }
        List<contact> deleteContact= new List<contact>();
        for(id id1:deleteCountContactMap.keyset()){
            for(integer i=0;i<deleteCountContactMap.get(id1);i++){
                deleteContact.add(deleteContactMap.get(id1)[i]);
            }
        }
        if(deleteContact.size()>0){
            delete deleteContact;
        }
    }
}

In case you find any other issue please mention. 
If you find your Solution then mark this as the best answer. 

 
snehil kumarsnehil kumar

@Suraj

Thanks again for your response.

Could you please help me to write the same trigger with best practice.
 

Suraj Tripathi 47Suraj Tripathi 47
Hi snehil,
Please take reference from this below trigger code with best practise and also this trigger fulfil your requirements.
trigger accountTrigger on Account (after insert,before update) {
    if(Trigger.IsAfter && Trigger.IsInsert){
        list<contact> connList= new list<contact>();
        for(account acc: trigger.new){
            for(integer i=0;i<Integer.valueOf(acc.NumOfContact__c);i++){
                contact con= new contact();
                con.LastName='test';
                con.AccountId=acc.Id;
                connList.add(con);
            }
        }
        if(connList.size()>0){
            insert connList;
        }
    }
    if(Trigger.IsBefore && Trigger.IsUpdate){
        map<id,account> accList=new map<id,account>([select id,NumOfContact__c,(select accountid,Lastname,id from contacts) from account where id IN: trigger.old]);
        map<id,integer> insertCountContactMap= new map<id,integer>();
        map<id,integer> deleteCountContactMap= new map<id,integer>();
        map<id,List<contact>> deleteContactMap= new map<id,List<contact>>();
        
        for(account oldAcc:trigger.old){
            for(account newAcc:trigger.new){
                if(oldAcc.id==newAcc.id && oldAcc.NumOfContact__c!=newAcc.NumOfContact__c){
                   if(oldAcc.NumOfContact__c<newAcc.NumOfContact__c){
                        integer diff=Integer.valueOf(newAcc.NumOfContact__c)-accList.get(oldAcc.id).contacts.size();
                        insertCountContactMap.put(oldAcc.id,diff);
                    }
                    else{
                        integer diff=accList.get(oldAcc.id).contacts.size()-Integer.valueOf(newAcc.NumOfContact__c);
                        deleteCountContactMap.put(oldAcc.id,diff);
                        deleteContactMap.put(oldAcc.id,accList.get(oldAcc.id).contacts);
                    }
                }
            }
        }
        List<contact> insertContact= new List<contact>();
        for(id id1:insertCountContactMap.keyset()){
            for(integer i=0;i<insertCountContactMap.get(id1);i++){
                contact con= new contact();
                con.Lastname='test '+i;
                con.AccountId=id1;
                insertContact.add(con);
            }
        }
        if(insertContact.size()>0){
            insert insertContact;
        }
        List<contact> deleteContact= new List<contact>();
        for(id id1:deleteCountContactMap.keyset()){
            for(integer i=0;i<deleteCountContactMap.get(id1);i++){
                deleteContact.add(deleteContactMap.get(id1)[i]);
            }
        }
        if(deleteContact.size()>0){
            delete deleteContact;
        }
    }
}
In case you find any other issue please mention. 
If you find your Solution then mark this as the best answer.