UI Tips and Tricks – Picture Upload

In the very early 90s I was employed as a professional Visual Basic programmer (and no that isn’t a contradiction in terms) enjoying greatly the development of client-server accounting systems. Good times. In those days tips and tricks sites were a big part of how the community shared knowledge. Following some recent reminiscing, through this series of posts, I’ll share some UI tips and tricks that aren’t necessarily an architects concern however I hope will prove helpful to some.

Ok, so down to business. Today’s tip concerns the upload and display of record images in the context of standard functionality, for example a Product image or Contact photo. The latter I’ll use as an example.

1. Add a field to Contact named [Photo Document Id], of the text type, 18 char length.

2. Add a field to Contact named [Photo], of the text formula type, formula set as below.
[sourcecode language=”xml”]

3. Add a Visualforce page named ContactPictureUploader, with no markup between the page tags.
4. Add an Apex class ContactPictureUploaderController, code as below, set as the VF page controller and ensure the page action is set to the initialise method.
[sourcecode language=”java”]
public with sharing class ContactPictureUploaderController {
private Id contactId;

public ContactPictureUploaderController(){
contactId = ApexPages.currentPage().getParameters().get(‘cid’);

public PageReference initialise(){
List<Attachment> listA = [select a.Id from Attachment a
where a.createdById =:UserInfo.getUserId()
and a.parentId=:contactId order by a.createdDate desc limit 1];
if (listA.size()>0){
Id attachmentId = listA[0].Id;

Contact c = [select Id from Contact where Id=:contactId];
c.Photo_Document_Id__c = attachmentId;
update c;
return new PageReference(‘/’+contactId);
VF Page markup.
[sourcecode language=”html”]
<apex:page controller="ContactPictureUploaderController" action="{!initialise}">
<!– Controller context page – no markup –>

5. Add a custom button to the Contact object of the JavaScript type, named Upload Photo, script as below.
[sourcecode language=”javascript”]

In short, the solution works by invoking the standard attachment page, which on submit redirects to the VF page which copies the uploaded document id to the Contact Photo Document Id field, then redirects back to the contact record. The image field on the Contact object then loads the image using the IMAGE() formula field, easy. The image field can then be used on the contact layout, related lists etc..