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
raj jordanraj jordan 

trigger to update the related fields?

i want to create description custom fields on account and contact object
now i want to create a trigger on account object such that when i insert a record on account object contact shoul also be created with with the custom field updated same as account
please help me to achieve this 

 
Waqar Hussain SFWaqar Hussain SF
You can accomplish this requirement using process builder. 
Sandeep YadavSandeep Yadav
Hi Jordan,
Description is already standard field on Account object and as well as on Contact object. You don't need to create this field on both objects.
trigger UpdateContactField on Account (after insert, after update)
{
    List<Contact> con = new List<Contact>();
     
    for(Account a : Trigger.new)
    {
        if(a.Description != null)
        {
            Contact ct = new Contact();
            ct.lastname = a.name;
            ct.AccountId = a.Id;
            ct.Description = a.Description;
            
            con.add(ct);
        }      
    }
    
     insert con;
}
Mark this best answer if this helps.
Thank you.
raj jordanraj jordan
Thanks Sandeep for ur answer but if I want to do it with any of the custom field how can I do this task?
 
raj jordanraj jordan
hi Sandeep,
i have done this and am getting the required result 
but when am updating account another contact is being created but i want the same inserted contact to get updated
help me to achoeve this

Thanks,
Jordan
 
Shamsi 110Shamsi 110
trigger UpdateContactField on Account (after insert, after update)
{
    List<Contact> con = new List<Contact>();
    Set<Id> setOfAccounts = new Set<Id>();
    for(Account acc :Trigger.New)
    {
        setOfAccounts.add(acc.Id);
    }
    List<Contact> accountContacts = [Select id,name,description from contact where accountid in :setOfAccounts]
    
    for(Account a : Trigger.new)
    {
        if(!accountContacts.size()>0 && a.Description != null)
        {
            Contact ct = new Contact();
            ct.lastname = a.name;
            ct.AccountId = a.Id;
            ct.Description = a.Description;
            
            con.add(ct);
        }
            
        else if (a.Description != null){
        for(Contact c : accountContacts)
        {
            c.Description = a.Description;
            con.add(ct);
        }
        }
    }
    
     upsert con;
}

Mark this best answer if this helps.
Thank you.