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
ajay ambatiajay ambati 

trigger issue while updating existing records

iam ajay iam having contacts are not associated with accounts iam goal is if contact not having accountname i,e lookup feild in contact so, i need to give accountname i,e SONY which having in existing accounts for all contacts so iam trying but recurssive trigger error iam finding to avoid yhat iam created class with boolean  static variable and accesed in trigger yhat you can found below
 CLASS:
public class avoidrecurssive 
{
public static boolean firstrun=true;
     
}

TRIGGER:
trigger childtoparent on Contact (before update) 
{
    if(trigger.isbefore)
    {
        if(trigger.isupdate)
        {
   
list<schema.contact>  c =  new list<schema.contact>();
account a = [select id,name from account where name ='sony'];
c=[select id,name,accountid from contact where accountid = null ];
   
for(schema.contact cn:c)
{  
    if(avoidrecurssive.firstrun)
      {   
    avoidrecurssive.firstrun=false;
      cn.Accountid = a.id;
        update cn;
     
    }
}
  
      }
    }
}

SCRRENSHOT OF ERROR:
while updating existing contacts
User-added image
Felix van Hove 9Felix van Hove 9
If I understand you correctly, you don't need an additional class. The trick is NOT to update anything in your trigger code. The update will be done automatically after your BEFORE UPDATE trigger is executed. You might want something like this:

    final Id defaultAccount = [SELECT Id FROM Account WHERE Name = 'Sony'].Id;
    for(Contact c:Trigger.new) {
        if(c.AccountId==null) {
            c.AccountId = defaultAccount;
        }
    }
Nithesh NNithesh N
Lets try it this way.
trigger childtoparent on Contact (before update) 
{
if(trigger.isbefore)
{
    if(trigger.isupdate)
    {
       account a = [select id,name from account where name ='sony' LIMIT 1];
       for(Contact C: Trigger.New){
         if(C.accountid == null){
               C.accountid = a.id;
            }
         }
     }
 } 

}

This should work for your use case, No need to update the record in an before update trigger as DML update will eventually applied to the record after code logic. No Recursive Events should occur too, But if it happens, you can use that static boolean approach with this code logic. 

Let me know if it works.