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
Anjana Sharma 9Anjana Sharma 9 

I have a custom field in my account object , i want that the values in my custom field add to contact object

trigger AccountTrigger1 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 = acc.Name;
            con.LastName = acc.Name;
            con.AccountId = acc.Id;
            acc.Contacts__c = con.firstname + ' ' +  con.LastName;
            lstAccount.add(acc);  
            lstContact.add(con);
                
            }
        }
        if(lstContact.size() > 0){ 
            insert lstContact;
            
        }
        if(lstAccount.size() > 0){
            update lstAccount;
        }
    }
}

This is my code but in this but i want that i add first name and last name during inserting a new account.For example i add a new account the add firtsname='helo' , lastname='world' in my custom fild in that format then it add that field values to contact , i can add multtiple contact through this field
Ajay Patel 54Ajay Patel 54

Hii  Anjana 

Here in these code you are passing the Name and in Name {First and last name is already concatenated} so just add simple  

 acc.Contacts__c = con.Name;

and also you are passing the 

First Name  and Last name  =Account Name 

for ex if Account name is Test name then 

con.firstname = acc.Name;    (output =Test name)
 con.LastName = acc.Name;   (output = Test Name)

and when passing            

acc.Contacts__c = con.firstname + ' ' +  con.LastName;   (output =Test name Test name )

Please mark it as Best Answer if it helps you.
Thanks & Regards
Ajay Patel

Suraj Tripathi 47Suraj Tripathi 47
Hi Anjana,

Greetings,

use this Code : 
trigger AccountTrigger1 on Account (after insert ) {
    if(trigger.isAfter && trigger.isInsert){
        list<Contact> lstContact = new list<Contact>();
            for(account acc : trigger.new){
            contact con = new contact();
            con.firstname = acc.Name;
            con.LastName = acc.Name;
            con.AccountId = acc.Id;
            acc.Contacts__c = con.firstname + ' ' +  con.LastName; 
            lstContact.add(con);
            }
        if(lstContact.size() > 0){ 
            insert lstContact;
        }
    }
}

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

Thank you!

Regards,
Suraj Tripathi