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
neshnesh 

TRIGGER:How to UPDATE account field to on (Update)contact field. please guide me

I HAVE ACCOUNT AND CONTACT RECORD DATA. UPDATE ACCOUNT FIELD TO CONTACT FIELD.HERE I DONT WANT TO WORKFLOW..I WANT TO UPDATE 20 FIELD ON CONTACT OBJECT  LIKE ADDRESS ,ZIPCODE,WEBSITE ETC.Account lookup field for contac.
MY TASK IS: WHEN UPDATE Createcontact__cCHECKBOX FIELD  ON CONTACT OBJECT-ALL 20 FIELD UPDATE FROM ACCOUNT TO CONTACT OBJECT.Createcontact__c (CHECK BOX FIELD ) IS A WORKFLOW FIELD UPDATE.. how to pull account field to on (Update)contact. field. please guide me
my code is :
trigger updatecontact1 on  Contact (after insert)
{
    Contact acc=Trigger.new[0];
    Contact aco=Trigger.old[0];
    account tt =new account();
   if(acc.Createcontact__c== TRUE && aco.Createcontact__c!= TRUE )
       {
      
       system.debug('@@'+aco.Createcontact__c);
        integer cont = [ select count()  from contact where accountid=:tt.id ];
        system.debug('@@'+cont);here i got zeo row.
         if (cont==1)
         {
        
          acc= [ select id,Address_1__c from Contact where accountid=:tt.id ];
          acc.Address_1__c=tt.Address_1__c;
          update acc;
          }
         
          }
          }
hitesh90hitesh90
Hello nesh,

Your trigger will not work for bulk of record. i will work only for single record at a time.
so you have to bulkify your trigger code as below.

Apex trigger:
trigger updatecontact1 on  Contact (after insert){
    List<contact> lstConUpdate = new List<Contact>();
    set<Id> sAccId = new set<Id>();
    for(Contact con: trigger.new){
        sAccId.add(con.AccountId);
    }
    List<Account> lstAccount = [select id, Address_1__c, (select id,Address_1__c from contacts) from account where id IN: sAccId];
    for(Account acc: lstAccount){
        for(Contact con: acc.contacts){
            con.Address_1__c = acc.Address_1__c;
            lstConUpdate.add(con);
        }
    }
    if(lstConUpdate.size() > 0){
        update lstConUpdate;
    }   
}


Thank You,
Hitesh Patel
SFDC Certified Developer & Administrator & Advanced Administrator & Sales cloud consultant
My Blog:- http://mrjavascript.blogspot.in/