Adding a Change Owner link to a Visualforce page
Posted By: Alex.Cottner on January 4th, 2013 in General
No Gravatar

We ran into an interesting limitation with VisualForce. It looks like when you use an apex:outputField on an owner field, the “Change” link doesn’t show up correctly. After searching through the SalesForce forums and some other blog posts I couldn’t find any solution that would work exactly like the standard Owner control works on a normal SalesForce page. The other solutions I found required having a separate “Change Owner” button, or using an output field. I wanted to keep this as close to stock as possible, so I figured the easiest thing to do would be to inject a “Change” link and park it right inside the outputField’s span.

Since this page already has some dojo code on it, I figured that would be the easiest route.

First, I need a way to easily identify my owner control on the page. So to do that I just set the id of the control to owner. While this is really meant to identify the control server side, it does stick “owner” at the end of the client side ID as well, and that is what I’m after.
<apex:outputField value="{!Account.OwnerId}" id="owner" />

Next all I had to do was inject a link next to the span the output field generates. To do that, all I had to use was a bit of dojo.
dojo.place('<a href="/{!Account.id}/a?retURL=/apex/ClientAccount?id={!Account.id}" style="padding-left: 10px;">[Change]</a>', dojo.query("[id$=\"owner\"]")[0], "last");

Breaking this down briefly…
The first portion is just my hyperlink to the change owner page. I’m adding 10 pixels of padding just so it doesn’t run into the owner’s name.
The dojo.query is returning an array of elements who’s ID ends in the word “owner”. This array only has one element on my page (the span the outputField creates) so I’m just grabbing the first item in it.
The word “last” is just telling it to put my anchor tag at the end of the span.

And there we have it, an owner control that functions correctly in a VisualForce page. Hopefully SalesForce will get this fixed soon as it’s pretty silly to have to do this.


Leave a Reply