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
hermitagehermitage 

Apex triggers

Hi ,

I am trying to learn writing apex triggers. I tried to updte the annual revenue field with 100000, if the account name is abs., but i am unable to succeed in writing this code. Can anyone suggest me or correct me.

 

trigger test1 on Account (before insert, before update) {
list<account> a= new list<account>();
for(account acc: [select id, name from account limit 10])
{
if(acc.name=='abs')
 acc.annualrevenue='100000';
}
}

trigger test1 on Account (before insert, before update) {
list<account> a= new list<account>();
for(account acc: [select id, name from account limit 10]){if(acc.name=='abs') acc.annualrevenue='100000';
}}

gtindugtindu

You wouldn't use a trigger for this use case.  Triggers are used to perform updates on the records being created/updated/deleted - or on a relationship to them.

You wouldn't use it to lookup a record standalone and update it directly.

Perhaps if you explained the use case for this with more detail.

TbomTbom

I agree with gtindu.  You could just do what you describe in your post with native Workflow and Field Update.

 

If you did want to write this in a trigger you would want to make the trigger bulk safe.  Something like this would do the trick:

 

 

trigger test1 on Account ( before insert, before update ){
  for(Account acct : trigger.new){
    if(acct.name == 'abs'){
      acct.annualrevenue__c = 100000;
    }
  }
}

 

 

Sai harsha 7Sai harsha 7
trigger updateannualrevenue on Account (before insert,before update) 
{
   
   list<Account> aclst = new list<Account>();
   
   if(trigger.isbefore)
   {
     if(trigger.isInsert)
     {
       for(Account a : trigger.new)
       {
         if(a.Name == 'abc')
         {
            a.annualrevenue = 100000;
            
          }  
         aclst.add(a);
       }
     }
   }      

   

   if(trigger.isbefore)
   {
     if(trigger.isUpdate)
     {
       for(Account a : trigger.new)
       {
           account oldaccount = Trigger.oldMap.get(a.ID);
           
           if(a.annualrevenue!=null)
           {
             if(a.annualrevenue != oldaccount.annualrevenue)
             {
               a.annualrevenue = 100000;
               
             }
             
           } 
           else
           {
             a.annualrevenue = 100000;
             
           }       
              aclst.add(a);

        }
        
      }
    }
    
     


}

you can try this code. please mark it as best answer and solved. 

Thanks & regards
Srikanth
salesforce Developer