+ Start a Discussion

update opportunity after update

No one can answer to this question?
Is it possible to update a field in an existing opportunity using an after update trigger?  I'm trying to get the id of the new owner of the opportunity, but I get read only when executing the trigger after update.  If I use before update, the id of the owner is the old owner and not the new one.
Here is the code to my trigger and class:
trigger UpdateOpportunityOwnerRole on Opportunity (before update) {

public class OpportunityOwnerRole {

public static void UpdateOwnerRole(Opportunity[] opps) {
  Opportunity opp = [select ownerid from Opportunity where id in :opps];
  Id oid = opp.ownerid;
  User role = [select userroleid from User where id = :oid];
  Id urid = role.userroleid;
  UserRole userrole = [select name from UserRole where id = :urid];
  String strownerrole = userrole.name;
  for (Opportunity op: opps) {
   op.owner_role__c = strownerrole;

I need to get the owner id that has changed?  How can I do this?
Thanks for any help.

Message Edited by Dman100 on 08-21-2008 07:10 PM
Presumably you're passing in the opportunities from Trigger.new?

Could you tell us what line the error occurs on?

Hi garyb,

The code listed in my original post runs fine.  I'm not getting any errors.  The trigger fires before the update occurs, so it grabs the id of the existing owner and not the new owner.

If I change the trigger to fire after the update occurs, then I get the read only error.

So, the only difference is when I try to fire the trigger after update instead of before update.

The flow goes like this: You have an existing opportunity >> change opportunity owner >> get id of new owner >> fire trigger to update opportuity.

Does that make sense?

Thanks for your help.

By the time 'after update' runs, the record has been committed back to the database.  You'll deadlock if you edit it again.  :-(

You just want opportunities to have a field with the owner's role, right?  I think maybe a formula field could do this?  Or insert a child object on the opportunity (in the after trigger) that contains this string, and then have the opportunity field look up from this child.

Had this problem.  Solved it (but I doubt if it is a best practice) by:

1) Select the same objects in a query in an afterUpdate

2) Set the field

3) Set up the "prevent recursive trigger" code type example from the Apex cookbook

4) Update the selected objects


if (Trigger.isUpdate && Trigger.isAfter ) {

  List<...> objs = [select ... from .. where Id in :IdList];

  for (... tmp : objs) {

      tmp.xxx = yyy;


  update objs;
I personally am surprises this seemed to work for me.

Message Edited by wsmith on 09-15-2008 03:01 PM

Message Edited by wsmith on 09-15-2008 03:01 PM