Thursday, December 16, 2010

Generating Barcode image on Visualforce and Formula Field: Salesforce Code Tip

Can we generate bar-code image on Visualforce? Yes, Can we make it a field on page layout? Also yes.
There are many API's available that help us achieve that. One such API is from http://www.searchupc.com. The API is very easy to use.

Visualforce usage:
1. The {!variable} will possibly be the SobjectVariable ({!sobject.fieldname}) or some {!variable} that stores the UPC code(possibly generated from algorithm.)

The output:

Formula Field Usage:
i) Create a formula field with output as 'Text'
ii) Use the below formula, replacing the mergeField with the field you store your UPC number.

image("http://www.searchupc.com/drawupc.aspx?q="+ mergeField ,"Barcode")

The Output:

Works like a charm.

Word of Caution: 
i) The API accepts only 12 and 13 digit of UPC number. Any other digit and it does not render image.
ii) The data is obviously not secure as we are passing the UPC code as a plain text to the server, there is a risk of packet sniffers.

That is it, displaying Barcode on Salesforce. If you find it useful, don't forget to drop in a comment down there, I wouldn't mind if you would prefer putting your name and comment behind a blank cheque and dropping it to my PO box, well, the method below the post seems easy and cheap no?