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
MallikMallik 

Before Trigger on Contact to set a custom field to a value in the corresponding Account Object.

I want put a trigger on contact. When ever a contact is created and Account is tied to it then I want to set custom field Acct_Industry__c to the value of the industry in the Account Object. 

I know it is basic scenario question but I am new to salesforce. Any help is appreciated. 
MallikMallik
I have writting something but considering the SOQL query in the loop there should be better solution than this. Please suggest

trigger Contact_Trigger on Contact (before Insert, before Update, After Insert, After Update) {
    If(Trigger.isBefore){
        If(Trigger.isInsert){
               For(Contact con:Trigger.New){
                If (con.AccountId != Null){
                     Account Acct = [Select Industry from Account where Id = :con.AccountId LIMIT 1];
                     con.Acct_Industry__c = Acct.Industry;
                }
                
           }
         }
    }
sfdcMonkey.comsfdcMonkey.com
hi Malllk
yes its not good coading skill that use SOQL inside for loop
try this below code
 
trigger Contact_Trigger on Contact (before Insert, before Update, After Insert, After Update) {
  List<id> accID = new List<id>();
  for(contact c : trigger.new){
     If (c.AccountId != Null){
        accID.add(c.AccountID);
        
        }
      }
  
    If(Trigger.isBefore && Trigger.isInsert){        
       List<Account> Acct = [Select Industry from Account where Id IN: accID ];

        For(account acc : Acct ){
            For(Contact con:Trigger.New){
                If(con.AccountId != Null){
                   Acct_Industry__c = acc.Industry ;
                }   
              }
          }
       
        }
    }

I hop it helps you
Please mark it best answer if it helps you so it make proper solution for others
Thanks