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
turbobuickturbobuick 

Code to update Record Owner to Current User ID - Help!

Hi All,

 

I'm very (very) new to Apex code development but am trying to accomplish a simple task. I have a custom button that points to a VisualForce where I intend to call a short code through a controller. I need the block of code to take a simple action: update the record owner Id (on the Account object) to the current user's ID who has just clicked the button. Simply, this button allows someone to 'claim' an Account. 

 

Any help at all would be greatly appreciated - I'm failing miserably at writing the code!

 

Thx.

Best Answer chosen by turbobuick
kevoharakevohara

I havent tested it but something like this should work.  Just create a new custom button on Account and select onClick Javascript.  Then just copy/paste the code below.  This will reassign the owner, then reload the screen for you to show the updates.

 

{!REQUIRESCRIPT('/soap/ajax/20.0/connection.js')}

var acc = new sforce.SObject('Account');
acc.Id = '{!Account.Id}';
acc.OwnerId = '{!$User.Id}';
sforce.connection.update([acc]);

location.reload(true);

 

All Answers

kevoharakevohara

If the only function that your Visualforce page provides is to reassign the owner, why not use a custom onclick javascript button instead?  This custom button could simply reassign the owner and reload the page.

 

If you do need a VF page, can you post your page and controller so far so we can help you.  But again, I really think all you need is a javascript button.

turbobuickturbobuick

Hi there,

 

I had originally thought of using a VF page to call a controller so the end user would see a splash page, but I agree that it could be accomplished with onclick javascript. For simplicity, let's start with that.

 

Could you provide some sample code to use as a template that accomplishes what I need to do?

 

I'm trying to accomplish:

For account record where user clicks button, grab current user ID and update OwnerId field on the Account record.

kevoharakevohara

I havent tested it but something like this should work.  Just create a new custom button on Account and select onClick Javascript.  Then just copy/paste the code below.  This will reassign the owner, then reload the screen for you to show the updates.

 

{!REQUIRESCRIPT('/soap/ajax/20.0/connection.js')}

var acc = new sforce.SObject('Account');
acc.Id = '{!Account.Id}';
acc.OwnerId = '{!$User.Id}';
sforce.connection.update([acc]);

location.reload(true);

 

This was selected as the best answer