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
Sana123Sana123 

I have a custom field in my account object , i want that when i add new account then new contact also add which i mention in my custom field

custom field in account object = Contact_detail
In this custom field i add firtsname = 'test' Lastname ='test2'
then this contact detail add t contact object by aplying trigger on account
ravi soniravi soni
hello sana,
try following code.
trigger addContactWhenAccountInsert on Account (after insert) {
    if(trigger.isAfter && trigger.isInsert){
        list<Contact> lstContact = new list<Contact>();
        list<Account> lstAccount = new list<Account>();
        set<Id> setAccountIds = new set<Id>();
        for(account acc : trigger.new){
            setAccountIds.add(acc.Id);
            }
        if(setAccountIds.size() > 0){
            for(account acc : [SELECT Id,Name From Account Where Id In : setAccountIds]){
            contact con = new contact();
            con.firstname = 'test';
            con.LastName = 'test2';
            con.AccountId = acc.Id;
            acc.Contact_detail__c = con.firstname + ' ' +  con.LastName;
            lstAccount.add(acc);
            
            lstContact.add(con);
                
            }
        }
        if(lstContact.size() > 0){ 
            insert lstContact;
            
        }
        if(lstAccount.size() > 0){
            update lstAccount;
        }
    }

}

let me know if it helps you and marking it as best answer.
Thank you
Sana123Sana123
Thanku for your rply but the if i want to add the first and last name during the new insert if account means the no of contacts i added or there name are not fix so how can i do that
Suraj Tripathi 47Suraj Tripathi 47

Hi,

Please find the solution.

trigger addContactWhenAccountInsert on Account (Before insert) {
    if(trigger.isAfter && trigger.isInsert){
         list<Contact> ContactList = new list<Contact>();
        
        for(Account ac: trigger.new){

                Contact con=new Contact();
                con.lastName=ac.Name;
                ac.Contact_detail=ac.Name;
                ContactList.add(con)
                                     }
        if(ContactList.size() > 0){ 
            insert ContactList;
            
        }
        
    }

}

Please mark it as the Best Answer if it helps you

Thank You

Sana123Sana123
How can I do insert update and delete with helper class for the same