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
Sunny NarulaSunny Narula 

Need to change record OWNER from Apex for a custom object.

I m using salesforce email service and have created a email parser(Controller) to extract the data from incoming email for a custom object.

Everything works with the default owner. But the requirement is to change the record owner. When the set the OwnerID to desired owner is gives the following error

"EXCEPTION_THROWN [548]|System.DmlException: Insert failed. First exception on row 0; first error: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on cross-reference id:"

Please let me know what I need to set to make the controller class change the Owner for this custom object.

Thanks in advance
Sunny

Amit Chaudhary 8Amit Chaudhary 8
Can you please post your code.
Sunny NarulaSunny Narula

Hello Amit,
As it is parser (extracting data from email), putting complete code here.. will just make it to long.
It runs perfect when I do not assign owner (default owner) for the record, when we change the owner to another user it give the above error

Let me explain the process..

a) Break in coming email on newline
b) Find unique words from the email (template)
c) Populate required custom object. (for changing the Owner... I m updating OwnerId property before saving the object.)
d) Insert the object to database.

thanks in advance..
Sunny

Vishal Kashyap 31Vishal Kashyap 31
The reason is because you don't have access to User record and User OWD is set to private.
Gopi AGopi A
Hello Amit,

I am trying to change the Accounts Owner Id from one user to another User as bulk at a time with out any CPU Limit error. the below one is the batch class and i want use this class in vf page. Could you help on this like how can we update using vf page 


global class AccountOwnerReassignment implements 
             Database.Batchable<SObject>, Database.Stateful{
    
    User fromUser{get; set;}
    User toUser{get; set;}
    Double failedUpdates{get; set;}
 
    global AccountOwnerReassignment(User fromUser, User toUser){
        this.fromUser = fromUser;
        this.toUser = toUser;
        failedUpdates = 0;
    }
    
    global Database.queryLocator 
                    start(Database.BatchableContext ctx){
        return Database.getQueryLocator([SELECT id, name, ownerId 
                        FROM Account WHERE ownerId = :fromUser.id]);
    }
    
    global void execute(Database.BatchableContext ctx, List<Sobject>
                        scope){
        List<Account> accs = (List<Account>)scope;
        
        for(Integer i = 0; i < accs.size(); i++){
            accs[i].ownerId = toUser.id;
        }
        
        List<Database.SaveResult> dsrs = Database.update(accs, false);
        for(Database.SaveResult dsr : dsrs){
            if(!dsr.isSuccess()){
                failedUpdates++;
            }
            
        } 
    }
    
    global void finish(Database.BatchableContext ctx){
    
        AsyncApexJob a = [SELECT id, ApexClassId, 
                       JobItemsProcessed, TotalJobItems, 
                       NumberOfErrors, CreatedBy.Email 
                       FROM AsyncApexJob 
                       WHERE id = :ctx.getJobId()];
        
        String emailMessage = 'Your batch job '
             + 'AccountOwnerReassignment '
             + 'has finished.  It executed ' 
             + a.totalJobItems 
             + ' batches.  Of which, ' + a.jobitemsprocessed 
             + ' processed without any exceptions thrown and ' 
             + a.numberOfErrors +
             ' batches threw unhandled exceptions.'
             + '  Of the batches that executed without error, ' 
             + failedUpdates 
             + ' records were not updated successfully.';
        
        Messaging.SingleEmailMessage mail = 
              new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {a.createdBy.email};
        mail.setToAddresses(toAddresses);
        mail.setReplyTo('noreply@salesforce.com');
        mail.setSenderDisplayName('Batch Job Summary');
        mail.setSubject('Batch job completed');
        mail.setPlainTextBody(emailMessage);
        mail.setHtmlBody(emailMessage);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] 
                           { mail });
    }

}