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 Patel 54Ajay Patel 54 

i want to write a trigger to update teh description field on account if condition satify

i want to update the account filed Desc when any new account is created or update with the desc filed contain 12345

here is my code it not allowing me to create record!!!!!

Not allowing to crete record showing error

//updateDesc: execution of AfterInsert caused by: System.DmlException: Update failed. First exception on row 0; first error: MISSING_ARGUMENT, Id not specified in an update call: [] Trigger.updateDesc: line 11, column 1

Thanks is advance 

 


trigger updateDesc on Account (after insert,after update) {
  List<Account> accList = new List<Account>();
    
    for(Account acc : Trigger.new)
        if(acc.Description =='12345')
    {
        Account accountobj = new Account();
        accountobj.Description=' Test trigegr';
        accList.add(accountobj);
    }
    update accList;
}

 

JonathanFoxJonathanFox
So what your code is doing here - when an account is inserted or updated, you are creating a NEW record and then trying to carry out an update on it, but you can't as it's not a record whucgh is committed to the database.
 
for(Account acc : Trigger.new)
        if(acc.Description =='12345')
    {
        Account accountobj = new Account();
        accountobj.Description=' Test trigegr';
        accList.add(accountobj);
    }


//CHANGE IT TO THIS:


for(Account acc : Trigger.new){
        if(acc.Description =='12345')
    {
        acc.Description=' Test trigegr';
        accList.add(acc);
    }
}

You have your account record already from the Trigger.new list and you are itterating over it with 'acc'.

​​​​​​​A few other things I would do, is create a class and method to handle the logic, and pass Trigger.new into that. Keeps the logic out of the trigger and gives you access to more features such as 'with sharing'. But the basics are almost there! :)
Ajay Patel 54Ajay Patel 54
@Jonathan Fox SFDC
thanks fro reply

eroror while inserting the record
updateDesc: execution of AfterInsert caused by: System.FinalException: Record is read-only Trigger.updateDesc: line 7, column 1
Guilherme TavaresGuilherme Tavares
Hey Ajay, maybe you are trying to update the same record after it was inserted. Try changing your trigger event to before insert to overcome this error.
Ajay Patel 54Ajay Patel 54
@Guilherme Tavares
errror again
updateDesc: execution of BeforeInsert caused by: System.SObjectException: DML statement cannot operate on trigger.new or trigger.old Trigger.updateDesc: line 11, column 1