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
cpaynecpayne 

Trigger record ownership on custom object (Apex newbie)

I'm trying to assign record ownership on custom-object records as they are created via the API.  The custom object is called "Sales Quotes".  I would like to change the owner on each record from the login username used by the API to the same owner that is set on the Opportunity (Sales Quotes being related to Opportunity via lookup relationship). 
 
The preferred method would have been Workflow rule but the field update does not allow dynamic selection of user.  So I'm hoping this could be an easy Apex trigger that could run after each record is created.  Does anyone have any ideas to accomplish this easily and/or some sample code that would work?
 
Thanks from an Apex newbie!
mikefmikef
Yes this is an "easy" trigger to write and follows one of the basic use cases for Apex code.

Please follow this post.

The trigger in the post will give you the shell you need.

Iterate through the trigger and get a set of oppty Ids to query.
Query opptys and populate a map.
Iterate through again and change the ownerId on your inserted record.

You can use this logical progression on many use cases.
cpaynecpayne
OK, so I came up with this code, errors popped though in Eclipse (Eclipse newbie):

trigger OrderOwnerUpdate on Sales_Order__c (after insert) {
//change the owner of a custom object record to be the owner of the parent record
for (Sales_Order__c.OwnerId:Trigger.new){
    Opportunity.OwnerID query = [Select OwnerID from Opportunity where Id = :Sales_Order__c limit 1]
    Sales_Order__c.OwnerID = query.Opportunity.OwnerID;
}
}


Any suggested improvements?  Thanks for your time.
cpaynecpayne
So we tweaked the code and eventually got this:

trigger OrderOwnerUpdate on Sales_Order__c (after insert) {
//change the owner of a custom object record to be the owner of the parent record
// Declare the variable to hold the ID of the parent opportunity owner
ID MyOppId;
Sales_Order__c[] soc = Trigger.new;
for (Sales_Order__c s:soc) {
s.OwnerID = s.Opportunity__r.OwnerId;
}
}


But when running the code in the sandbox we get an error in the API:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"><meta name="ProgId" content="Word.Document"><meta name="Generator" content="Microsoft Word 11"><meta name="Originator" content="Microsoft Word 11">

Apex script unhandled trigger exception by user/organization: 00540000000wJBB/00D400000007Bwx

 

OrderOwnerUpdate: execution of AfterInsert

 

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

 

Trigger.OrderOwnerUpdate: line 7, column 1



The records we are creating including the Opportunity we are referencing are all set to Public Read/Write in the security model (hoping this code will help us change that) - so the error appears to be abit of a misnomer.  Any ideas?
mikefmikef
try making the trigger before insert
cpaynecpayne
Tried that, the error message from the API is now:

Apex script unhandled trigger exception by user/organization: 00540000000wJBB/00D400000007Bwx

OrderOwnerUpdate: data changed by trigger for field Owner ID: owner cannot be blank


Getting closer it looks like!  :)
mikefmikef
Code:
ID MyOppId;
Sales_Order__c[] soc = Trigger.new;
   for (Sales_Order__c s:soc) {
      if(s.Opportunity__r.OwnerId != null){
         s.OwnerID = s.Opportunity__r.OwnerId;
      }
   }
}

 
FreeFree
Hi all,

I would appreciate your help on this one:
I'm trying to achieve the following :
- A user can directly modify a Case which is in a Queue. In this case he automatically owns the case.
This business need is set to skip the step of taking ownership of the case before being able to modify it.

The problem is, I use a before update trigger on the case.
My algorithm is the following :
    if (owner is a Queue) // Je suis dans le cas d'une file d'attente
        {
        }
    else
       {
        Owner of the Case is the User Id
       }

My Code is fine, the only problem is I encounter the following issue :
Insufficient Privileges You do not have the level of access necessary to perform the operation you requested. Please contact the owner of the record or your administrator if access is necessary.

It only works with the admin (probably because he has "modify all data" permission on his profile.

I thought that if I changed the owner in the before update of the Case trigger it would work fine. But it doesn't, any idea ?

Thanks in advance !
cpaynecpayne
Do all users have the "Transfer Records" permission on their profile?
FreeFree
No they didn't
I just tried but it doesn't make any difference ! :-(
cpaynecpayne
Sorry, forgot cases had specific transfer permissions.  There are a couple more you can play with the settings - Transfer Cases and Manage Cases.  Check those and review the other permissions for the profiles you need....the fact that an Admin user can do it but the other users give you insufficient priv errors definetely makes me think the answer is in here.
FreeFree
Thanks for the help, unfortunately, those are ticked as well !!!

You're probably right, it's probably something having to do with permissions.
But I get the impression it's the "modify all data" which I cannot grant for regulat users.

The weird thing is that although I change ownership in the Apex Triger, basic security rules seem to apply first ?!
FreeFree

Anyone ? I'm getting desperate here :smileysad:

Seems pretty simple though !!!

paynecpaynec
Hi all, we finally figured this one out so wanted to make sure we shared the final version so that anyone with this issue in the future has the latest & greatest!
 
trigger OrderOwnerUpdate on Sales_Order__c (before insert,before update) {
//change the owner of a custom object record to be the owner of the parent record
// Declare the variable to hold the ID of the parent opportunity owner
    ID MyOppId;
    Sales_Order__c[] soc = Trigger.new;
    for (Sales_Order__c s:soc)
    {
       if(s.Opportunity__c!=null)
       {
           ID OpportunityOwnerId =[Select OwnerId from Opportunity where Id=:s.Opportunity__c].OwnerId;
           s.OwnerID = OpportunityOwnerId;
       }
   }  
}
mikefmikef
Please note this solution is not bulked.

refer to this post, for an example of bulking your triggers.
JohnC5674JohnC5674
May I ask for help here? How did you create the Test Class to move your trigger into production? I have a trigger that updates the lead owner based on information in a custom object to replace SFDC assignment rules, but I dont know how to create a test class to move it over.  Can someone please help?
mikefmikef
there are good examples in the Apex docs on creating test classes. When you deploy you just need to add your test class.
JohnC5674JohnC5674

Mikef,

I have looked at those docs but still not understanding it.  I am completely new to this.  Does anyone have some examples?

Thanks,

John

SalesforceSSOSalesforceSSO
when a user leaves the org. administrator uncheck the active checkbox for a user. Then a screen comes if we want to  transfer the ownership of open opp that belong to that user. can there be an automate process like a workflow or trigger so that when we make a user inactive, all his stuff ownership be changed to his manager name.
 
Please help.