MultiFile upload / Drag and drop Attachments

Attaching multiple files as attachments to records is a pain. Its takes lot of time plus lot of navigation. Today, I want to share a small piece of code that I have written as home page component which will inject a small section in the ‘Notes and Attachments’ related list which will allow the users to load multiple file either selecting it from the input file selection or the users can drag and drop the files.


So how do you implement this in your org.

1) Add the main script to a js file and add it to static resource.

2) Create a new Custom Link.

3) Reference the js file in the custom link you created in the previous step. We will also need jQuery, so we will add that as well.

4) Add that custom link a home page component of type Links.

5) Add the home page component to the home page layout and you’re done. For more details on this hacking method, you can check this link here

So here we go: ->

1) Create a javascript file with the below code and add it as a static resource with the name attachmentjs


    /*Checks when the notes and attachment section is loaded and then initiates the process.*/
    var timeInterval = setInterval(function(){
        if(jQuery("div.bRelatedList[id$=RelatedNoteList]").find("div.pbHeader").find("td.pbButton").find("input[name=attachFile]").length > 0){


/*Adds the drop zone div in the notes and attachment section. Event listener are added to listen when files are dropped in the zone.*/
function addAttachButton() {

    var attachmentDiv = jQuery("div.bRelatedList[id$=RelatedNoteList]");

        jQuery("<td>", {
            style   : "width:35%;cursor:pointer;"
                style : "height: 30px;  width: px;border-color: orange;border: 3px solid orange;border-style: dotted;border-radius: 4px;text-align: center;vertical-align: middle;line-height: 2;color: Red;font-family: monospace;font-size: 14px;",
                id : "dropDiv"
            }).append(jQuery("<span>",{id:"clickHere"}).text('Drop files here / click here!') , jQuery("<span>",{id:"uploadingMessage",style:"display:none;"}).text('Uploading your Files, please wait!'))

        if(jQuery("#uploadingMessage:hidden").length > 0) {
            if(jQuery("#multiUploadButton").length > 0) {
            }else {
        } else {
            alert('Your files are being uploaded. Please Wait!');

    function handleFileSelect(evt) {
        var files = evt.dataTransfer.files; // FileList object.
    function handleDragOver(evt) {
        evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.

    var dropZone = document.getElementById('dropDiv');
    dropZone.addEventListener('dragover', handleDragOver, false);
    dropZone.addEventListener('drop', handleFileSelect, false);

function processFiles(files) {
    var insertedFilesArray = [];
    var fileInsertionCounter = 0;

        for(i=0;i<files.length;i++) {
            var reader = new FileReader();
            reader.onload = (function(newFile,pId) {
                return function(e) {
                    var attachmentBody =',')+1,;
                        type: "POST",
                        url: "https://""/services/data/v33.0/sobjects/Attachment/",
                        contentType:"application/json; charset=utf-8",
                        headers: { 
                            "Authorization" : "Bearer "+getCookie('sid')
                        data    : JSON.stringify({'name','body':attachmentBody,'parentId':pId,'isprivate':false})
                    }).success(function(result) {
                        if(fileInsertionCounter == files.length){
                        alert('Unable to Insert file \n Contact your Adminstrator with this error message \n' + JSON.stringify(err));
                        //if all the files are uploaded then show the zone div.
                        if(fileInsertionCounter == files.length){

/*Inserts the input file button. This is hidden from the view.*/
function insertButton() {
    if(jQuery("#multiUploadButton").length == 0) {
        var attachmentDiv = jQuery("div.bRelatedList[id$=RelatedNoteList]");
                {id     : "multiUploadButton",
                value   : "Multiple Upload",
                type    : "file",
                multiple: "multiple",
                style   : "display:none;"

function hideDiv() {

function showDiv() {


function getCookie(c_name){
    var i,x,y,ARRcookies=document.cookie.split(";");
    for (i=0;i<ARRcookies.length;i++){
        if (x==c_name){
            return unescape(y);

2) Create a custom link called ‘Attacher Custom Link’ and the add the below code. Make sure you select Behaviour as ‘Execute Javascript’.


… follow all the steps mentioned above and you should be set. I have tested this on Latest Chrome and firefox browsers and this is working just fine.

node.js + ALM + REST API = Awesome

Everyday you see people (or yourself) doing some mundane task and you wonder how can you help them automate that process. So this article highlights something I did a few months back to help a friend who used to spend considerable amount of time fetching data from ALM (Earlier know as QC) formatting it and putting in some other database.

I always wanted to use node.js in something useful, so I decided to set up a server to get data from ALM server and push it to other database. Until this point I had no idea if ALM had exposed any API’s. Luckily they had opened up access to ALM 11.00 and higher version via their REST API. I wanted everything on server side and there was no UI involved.

So I was able to come up with a small script which authenticates the user into ALM and then get all the defect related to a release. I have provided the comments where ever necessary in the below code. I am still a noob in node.js so please excuse me if I have made any mistake

var https = require('https'),
	fs = require('fs'),
	config = JSON.parse(fs.readFileSync('config.json'));//this refers to a file where I have all my config like host, userName, password Etc

//this is added to avoid the TLS error. Uncomment if you get a TLS error while authenticating.
//process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0';

//set the correct options for the call.
var options = {
	host :, 
	path : "/qcbin/authentication-point/authenticate",
	method: "GET",
	headers : {'Authorization': 'Basic '+new Buffer(config.alm_userName + ':' + config.alm_password).toString('base64')}
	//authenticating the user into ALM
	ALMConnect(options, 'header','', function(status, data){
			//get the LWSSO_Cookie from the header. This is the session cookie which will be used in all callouts to ALM.
			if(data.headers["set-cookie"] != undefined ) {
				console.log('Dagnabbit!! ERROR:  Unable to login, check your username/password/serverURL.');
			console.log('Dagnabbit!! ERROR:  ' + JSON.stringify(data));

//Function to extract the defects for analysis.
function extractDefects(LWSSO_Cookie){
	var queryParam = "{";
	//add Release
	queryParam += "detected-in-rel["+config.release+"];";
	//add all your request parameters here. Its a little complicated initially, but you will get a hang of it. 
	// Make sure to use encodeURIComponents() for all the values in the query parameters.
	//get all the fields that you want to query. Lesser the fields smaller the XML returned, faster is the call.
	var fields = config.defectFieldMapping.fieldArray.join(',');
	var opt = {
		path: "/qcbin/rest/domains/"+config.domain+"/projects/"+config.project+"/defects?query="+queryParam+"&fields="+fields+"&page-size=max",
		headers: {"Cookie":LWSSO_Cookie}

	ALMConnect(opt, 'data','',function(status,data){
                        //write the defects to an XML file in local drive.
			//once you get the defectXML you can parse it into JSON and push it other databases like SFDC etc..		
			console.log('Dagnabbit!! ERROR:  ' + JSON.stringify(data));

function ALMConnect(opt, responseType,requestBody, callback){

	var request = https.request(opt, function(res){
		var XMLoutput='';
			}else {
				callback(true, res);
	if(opt.method=='POST' || opt.method == 'PUT'){

Showing a VF in jQuery modal dialog on standard page button click

Showing a VF page as a popup on click of a custom button is fairly easy. But the problem arises when we have to refresh the parent when the user has completed the operation on the VF pop-up page because of the same-origin policy. The browser doesn’t allow any communication across domain/ protocol. But as a workaround we can use the postMessage() to communicate between parent and pop-up window even if they are on different domain, but again IE8 doesn’t support this.

jQuery Modal Dialog to the rescue. In this demo we will place a custom button on the account detail page, clicking on which will pop-up a modal-vf page which will allow the user to update the name of the account.

I will be using 4 components to demo this :

1) A javascript file, stored in Static resource
2) An images zip file in static Resource. Click here to download the images zip file and store it in the static resource by the name images
3) A Custom button
4) An apex class (extension)
5) A VF page (pop-up)

Lets start with the javascript file. Store this in the static resource by the name mainjs

	/*@description: This script will insert a modal div in the standard page.
					the modal will contain a VF page. This file should be located in static resource.*/
	var j$ = jQuery.noConflict();
	var currentUrl = window.location.href;
	var hostIndex = currentUrl.indexOf('/')+('/').length;
	var accountId = currentUrl.substring(hostIndex,hostIndex+15); 
		/*Insert the jQuery style sheets in the Head.*/
		/*Insert the Modal dialog along with the VF as an iframe inside the div.*/
		/*Initialize the Dialog window.*/
			autoOpen: false,
			height: 210,
			width: 605,

Apex Class :

public class PopUpExtension{
    public Account account{get;set;}

    public PopUpExtension(ApexPages.StandardController stdController){
        this.account = (Account)stdCOntroller.getRecord();
    public void saveAccount() {
            update Account;
        }catch(exception e) {
            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Error Occured while updating the account '+e.getMessage());

VF page, name it as popuppage:

<apex:page showHeader="false" sidebar="false" standardController="Account" extensions="PopUpExtension">
        <apex:pageBlock title="{!Account.Name}" id="pageBlock">
            Update the Account Name:<br/>
            <b>Account Name</b><apex:inputField value="{!Account.Name}"/>
            <apex:commandButton action="{!saveAccount}" value="Save" onComplete="closeAndRefresh();" status="actionStatus" reRender="pageBlock"/>
            <apex:actionStatus id="actionStatus">
                <apex:facet name="start"> 
                    <img src="/img/loading.gif"/>
        function closeAndRefresh(){
            console.log('clicked on the button');
   = '/{!$}';

Finally create a button on the Account and call it jQuery modal. Select
‘Detail Page Button’ as the Display Type ,
‘Execute Javascript’ as the Behavior and
‘onClick JavaScript’ as content source.

Add the below code in the button:



For more info on the Dialog check out the doc here

Hope this helps!

Hiding selected Side bar custom components(HTML)

There are times in the project where we have to have some UI changes done on the Standard pages. For example, you may have to change the label of the ‘open Activities’ related list on a particular object’s standard page. To achieve this functionality we usually write a simple javascript / jquery script in the side bar component (of type HTML) and then that will do the work. So there are scenarios where multiple team might have implemented such functionality and this results in a lot of sidebar components showing up on the UI which will not make sense to the End Users

In the below code one have to just enter the name of the such side bar components and then that side bar component will be automatically hidden.

//Referencing the jQuery library from the static resource
<script src="/resource/jQuerylib"></script>
var j$ = jQuery.noConflict();
//Add All the name of the components that you want to hide.
var hideComponentArray = ['component1','component2','HideSideBarComponents'];
      if(j$.inArray(j$(this).text(), hideComponentArray) != -1){
         //Hiding the entire div.

Storing Javascript object in local storage

I was working on a chrome extension where I wanted to store javascript objects in localstorage and retrieve it later. But I was unable to do so with just setting the javascript objects in localstorage. I had to first stringify it and then parse it.

//create a javascript object array.
 var team = [{lead:'Monica',projectManager:'Ross',intern:'Chandler'},

//Store it in the localstorage and name it localStr.

//Retrieve the data and parse it back to JSON.
var retrieveData = JSON.parse(localStorage.getItem('localStr'));

//Write the data to the console.
console.log('and the lead of team 1 is '+ retrieveData[0].lead);

Using jQuery’s AutoComplete in Salesforce – Part 2

In the first part we saw that we are using a static array to show the country value. This is of no use in real-time scenario. In most of the cases one will be required to show the values from some where else. So how do we do it in salesforce??

In this example we will use the account and contact object to get the data.
Now, there are 2 ways to get the data from the database.
1.) Use a controller, which will return you a list of accounts.
2.) Query directly in the VF page using the Salesforce’s Ajax toolkit.


I will demonstrate both the ways in the same code.

Step 1: Create an apex class with the below code. The name of the class is AutoCompleteDemoController
Step 2: Create a the VF page with the below code. Name the VF page : AutocompleteDemoPage

Apex Class:

public class AutoCompleteDemoController{
    public list<account> getAccountList(){
        return [select id,name from account limit 25];

VF page:

<apex:page controller="AutoCompleteDemoController">
    <!--Make sure you have the Javascript in the same order that I have listed below.-->
    <script src=""></script>
    <script src="/soap/ajax/26.0/connection.js" type="text/javascript"></script>
    <script src=""></script>
    <link rel="stylesheet" href=""/>
    <script type="text/javascript">
        var j$ = jQuery.noConflict();
        var apexAccountList =[];
        //use the <!-- <apex:repeat> -->tag to iterate through the list returned from the class and store only the names in the javascript variable.
        <apex:repeat value="{!accountList}" var="accList">
            //Store the name of the account in the array variable.
        //We will establish a connection salesforce database using the sforce.connection.init(sessionID, ServerURL) function.
        var sid = '{!$Api.Session_ID}';
        var server = "https://" + + "/services/Soap/u/26.0";
        sforce.connection.init(sid, server);
        //We will query the contact object using the sforce.connection.query function. This will return 200 results.
        var result = sforce.connection.query("select Name from Contact");
        var records = result.getArray("records");
        var javascriptContactList =[];
        //Iterate thru the list of contact and store them in a javascript simple array variable which will then assign it to the source of the autocomplete.
        //on Document ready
                source : apexAccountList
                source : javascriptContactList
        <b>Account(This uses the Apex class to display the list)</b><input type="text" id="apexaccountautocomplete"/><br/><br/>
        <b>Contact(This uses the salesforce's ajax toolkit to display the list)</b><input type="text" id="sfjscontactautocomplete"/>

P.S:This code may not work correctly in Google Chrome Browser initially.
Workaround: When you load the VF page for the 1st time in Chrome, you will see a shield (gray in color) in the address bar, click on it and select ‘Load unsafe javascript’. Another option is to load the script in the static resource and refer the scripts from there in the VF page.

Using jQuery’s AutoComplete in Salesforce – Part 1

Using the Auto-Complete plugin enhances the UI functionality. Whenever a user enter a value in a input field, the auto-complete will show the user a possible set of value which matches the user input value.

Now, Just to show an example , I will use the auto-complete functionality on a country input field. When a user starts entering a value, based on his entry we will show the possible values. We will make use of the jQuery auto-complete plugin. This plugin makes it very simple to implement the autocomplete in salesforce, any HTML content for that matter.

In the first example we will use the plugin in a VF page then we will implement a similar functionality on a standard page.

Step 1: Create a VF page, I will name it AutoCompleteExample
Step 2: Copy the below code and save the page.
Step 3: Open the VF page you have just created (https://yourSaleforceInstance/apex/AutoCompleteExample). You will be able to see a input field, Start entering some text. Voila!! you will be able to see autocomplete in Action.

	<!--Make sure you have the Javascript in the same order that I have listed below.-->
	<script src=""></script>
	<script src=""></script>
	<link rel="stylesheet" href=""/>
	<script type="text/javascript">
		//Create a new variable j$ just to avoid any conflicts with other libraries which may be using $.
		var j$ = jQuery.noConflict();
		//Capture the list of countries in a Array.
		var countryArray = ['India', 'USA', 'China','FInland','Norway','Netherlands','England','Ukraine','Russia','Japan','Korea','Burma','Srilanka','Iran','Iceland','Canada','Rome','Australia','Armenia','Albania','Afghanisthan'];
		//on Document ready
				source : countryArray
		<b>Enter Text</b><input type="text" id="countryautocomplete"/>

P.S: This code may not work correctly in Google Chrome Browser initially.
Workaround: When you load the VF page for the 1st time in Chrome, you will see a shield (gray in color) in the address bar, click on it and select ‘Load unsafe javascript’.