+ Start a Discussion
shan876shan876 

Update a field based on another field??

Hi all:
I have a field "Site"... Now this field has to equal the same exact value that is in Status_Description which is a picklist. Now I have the following code that I try to write Obviously it is not working: Please help:
Code:
My Trigger
trigger accountsiteupdate on Account (after update) 
{
if (Trigger.isBefore){ 
Account[] accs=Trigger.new; 
acct_site_update.addacctsiteupdate(accs);
}
}

My Class
public class acct_site_update 
{
// This class updates the Account Site field on 
//account records that are
// passed to it.
public static void addacctsiteupdate(Account[] accs)
{
for (Account a:accs)
{
if (a.Site != a.Account_Status_Description__c) 
{
a.Site = a.Account_Status_Description__c;
}
}
}
}



 
Where did I got wrong?
Thanks
Shan
jeremyfrey1jeremyfrey1
You have an after update trigger, however, your code has if (Trigger.isBefore) as a condition.  After an update (after the records were saved), this will always be false, so the code inside that block would never execute.
shan876shan876
Thanks for te response... So I tried after update,after insert and tried isAfter, isBefore, isInsert
and nothing works....
Could someone give me a hint to making this right
Thanks
Shan
jeremyfrey1jeremyfrey1
Your trigger only handles after an insert.  Thus, you don't even need isBefore or isAfter.  You'd only need that if your trigger handles both before and after, to separate out what should happen in each case.  Take out the code and see if there's any additional errors or problems.  Also, be proactive and write a unit test now, rather than when you're ready to deploy; you may find the problem in doing so.
shan876shan876

hi:

 so I took the isbefore thing away and now I get this:

Apex script unhandled trigger exception by user/organization: 00550000000lxVc/00DT0000000Ec1z

accountsiteupdate: execution of AfterUpdate

caused by: System.Exception: Record is read-only

Class.acct_site_update.addacctsiteupdate: line 13, column 1
Trigger.accountsiteupdate: line 5, column 5

I know the record is not read-only... So I have no idea why is it stating that...

but let me ask something:

   I need the trigger to fire off when a.Site is null or not matching the value from the Picklist Status_Description. This could happen during an insert of a new record or an update to an old record. So should I be using after insert,after update and should I use Trigger.new plus the Trigger.old...

I am sooo confused..

But thanks for helping me out

Shan

jeremyfrey1jeremyfrey1
The record's read-only because you're not allowed to change fields using trigger.new after an insert.  There's a chart on page 169 of the Apex Developers Guide letting you know what you can / can't do.  Try changing the trigger to before insert, though you should take a look at that chart ot ensure you're doing exactly what you want to do.