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
AlecSAlecS 

Assigning an Opportunity to another User through trigger

I have written a trigger on Opportunity that creates another copy of the Opportunity at close time for renewal business.

 

However, this renewal opportunity should be owned by another user, let's say, Alec Sewart.

 

I have tried all these codes, but they don't work. How can I assign all renewal opportunity to Alec Stewart through trigger.

 

//option 1:
opp.OwnerId = [SELECT Id, name FROM User WHERE Name = 'Alec Stewart'].id;

//option 2:
opp.Owner.Name =  'Alec Stewart';

//option 3:
opp.Owner.FirstName = [select FirstName from User where name = 'Alec Stewart'].FirstName;
opp.Owner.LastName = [select LastName from User where name = 'Alec Stewart'].LastName;

 

 

Thanks.

Best Answer chosen by Admin (Salesforce Developers) 
crop1645crop1645

It is definitely option 1; you need to set OwnerId.  

 

[select id from User where name = 'Alec Stewart' limit 1]

 

Your error is that the SOQL query returns a list and you need to reference an element of that list:

[select id, anme from User where name= 'Alec Stewart'] [0].id

 of course, you will need to bulkify your trigger as many oppos could get closed in a batch and also handle queryExceptions where you can't find the renewal owner

 

All Answers

crop1645crop1645

It is definitely option 1; you need to set OwnerId.  

 

[select id from User where name = 'Alec Stewart' limit 1]

 

Your error is that the SOQL query returns a list and you need to reference an element of that list:

[select id, anme from User where name= 'Alec Stewart'] [0].id

 of course, you will need to bulkify your trigger as many oppos could get closed in a batch and also handle queryExceptions where you can't find the renewal owner

 

This was selected as the best answer
AlecSAlecS

Thank you, option 1 worked.