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.

dragndrop

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

jQuery(function(){

    /*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){
            addAttachButton();
            clearInterval(timeInterval);
        }
    },100);


});

/*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]");
    insertButton();

    attachmentDiv.find("div.pbHeader").find("td.pbButton").after(
        jQuery("<td>", {
            style   : "width:35%;cursor:pointer;"
        }).append(jQuery("<div>",{
                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!'))
        )
    );

    jQuery("#dropDiv").on('click',function(){
        if(jQuery("#uploadingMessage:hidden").length > 0) {
            if(jQuery("#multiUploadButton").length > 0) {
                jQuery("#multiUploadButton")[0].click();
            }else {
                insertButton();
                jQuery("#multiUploadButton")[0].click();
            }
        } else {
            alert('Your files are being uploaded. Please Wait!');
        }
    });

    function handleFileSelect(evt) {
        evt.stopPropagation();
        evt.preventDefault();
        var files = evt.dataTransfer.files; // FileList object.
        processFiles(files);
    }    
    function handleDragOver(evt) {
        evt.stopPropagation();
        evt.preventDefault();
        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) {
    hideDiv();
    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 = e.target.result.substring(e.target.result.indexOf(',')+1,e.target.result.length);
                        
                    jQuery.ajax({
                        type: "POST",
                        url: "https://"+window.location.host+"/services/data/v33.0/sobjects/Attachment/",
                        contentType:"application/json; charset=utf-8",
                        headers: { 
                            "Authorization" : "Bearer "+getCookie('sid')
                        },
                        data    : JSON.stringify({'name':newFile.name,'body':attachmentBody,'parentId':pId,'isprivate':false})
                    }).success(function(result) {
                        fileInsertionCounter++;
                        if(fileInsertionCounter == files.length){
                            showDiv();
                        }
                    }).fail(function(err){
                        alert('Unable to Insert file \n Contact your Adminstrator with this error message \n' + JSON.stringify(err));
                        fileInsertionCounter++;
                        //if all the files are uploaded then show the zone div.
                        if(fileInsertionCounter == files.length){
                            showDiv();
                        }
                    });
                };
            })(files[i],jQuery("div.bRelatedList[id$=RelatedNoteList]").attr('id').split('_')[0]);
            
            reader.readAsDataURL(files[i]);
        }
}

/*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]");
        attachmentDiv.find("div.pbHeader").find("td.pbButton").append(
            jQuery("<input>",
                {id     : "multiUploadButton",
                value   : "Multiple Upload",
                type    : "file",
                multiple: "multiple",
                style   : "display:none;"
                })
        );
        jQuery("#multiUploadButton").on('change',function(){
            processFiles(document.getElementById("multiUploadButton").files);
        });
    }
}

function hideDiv() {
    jQuery("#uploadingMessage").show();
    jQuery("#clickHere").hide();
}

function showDiv() {

    jQuery("#uploadingMessage").hide();
    jQuery("#clickHere").show();
    RelatedList.get(jQuery("div.bRelatedList[id$=RelatedNoteList]").attr('id')).showXMore(30);
}

function getCookie(c_name){
    var i,x,y,ARRcookies=document.cookie.split(";");
    for (i=0;i<ARRcookies.length;i++){
        x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
        y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
        x=x.replace(/^\s+|\s+$/g,"");
        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’.

  {!REQUIRESCRIPT('//code.jquery.com/jquery-2.1.3.min.js')}
  {!REQUIRESCRIPT('/resource/attachmentjs')}

… 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 : config.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){
		if(status){
			//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 ) {
				extractDefects(data.headers["set-cookie"]);
			}else{
				console.log('Dagnabbit!! ERROR:  Unable to login, check your username/password/serverURL.');
			}
		}else{
			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.
	queryParam+="}";
	//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 = {
		host: config.host,
		path: "/qcbin/rest/domains/"+config.domain+"/projects/"+config.project+"/defects?query="+queryParam+"&fields="+fields+"&page-size=max",
		method:"GET",
		headers: {"Cookie":LWSSO_Cookie}
	};

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

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

	var request = https.request(opt, function(res){
		res.setEncoding('utf8');
		var XMLoutput='';
		res.on('data',function(chunk){
			XMLoutput+=chunk;
		});
		res.on('end',function(){
			if(responseType=='data'){
				callback(true,XMLoutput);
			}else {
				callback(true, res);
			}
		});
	});
	request.on('error',function(e){
		callback(false,e);
	});
	if(opt.method=='POST' || opt.method == 'PUT'){
		request.write(requestBody);
	}
	request.end();
}


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(window.location.host+'/')+(window.location.host+'/').length;
	var accountId = currentUrl.substring(hostIndex,hostIndex+15); 
	j$(function(){
		/*Insert the jQuery style sheets in the Head.*/
		/*Insert the Modal dialog along with the VF as an iframe inside the div.*/
		j$("head").after(
			j$("<link>",{rel:"stylesheet",
						href:"https://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css"}));
		j$("body").after(
			j$("<div>",{id:"modalDiv",
					    style:"display:none;"
			   }).append(
				j$("<iframe>",{id:"vfFrame",
							 src:"/apex/popuppage?id="+accountId,
							 height:200,
							 width:550,
							 frameBorder:0})
			   ));
		/*Initialize the Dialog window.*/
		j$("#modalDiv").dialog({
			autoOpen: false,
			height: 210,
			width: 605,
			modal:true
		});
	});

Apex Class :

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

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

VF page, name it as popuppage:

<apex:page showHeader="false" sidebar="false" standardController="Account" extensions="PopUpExtension">
    <apex:form>
        <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"/>
                </apex:facet>
            </apex:actionStatus>
        </apex:pageBlock>
    </apex:form>
    <script>
        function closeAndRefresh(){
            console.log('clicked on the button');
            window.top.location = '/{!$CurrentPage.parameters.id}';
        }
    </script>
</apex:page>

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:

{!REQUIRESCRIPT("https://code.jquery.com/jquery-1.10.2.js")} 
{!REQUIRESCRIPT("https://code.jquery.com/ui/1.10.4/jquery-ui.js")} 
{!REQUIRESCRIPT("/resource/mainjs")}

j$("#modalDiv").dialog('option','title','{!Account.Name}').dialog('open');

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>
<script>
	
var j$ = jQuery.noConflict();
//Add All the name of the components that you want to hide.
var hideComponentArray = ['component1','component2','HideSideBarComponents'];
j$(function(){
   j$("h2.brandPrimaryFgr").each(function(){
      if(j$.inArray(j$(this).text(), hideComponentArray) != -1){
         //Hiding the entire div.
         j$(this).parent("div.sidebarModuleHeader").parent("div.htmlAreaComponentModule").hide();
      }
    });
});
</script>

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'},
	     {lead:'Joey',projectManager:'Rachel',intern:'Phoebe'}];

//Store it in the localstorage and name it localStr.
localStorage.setItem('localStr',JSON.stringify(team));

//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.

sfdcAutocomplete

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="https://code.jquery.com/jquery-1.8.2.js"></script>
    <script src="/soap/ajax/26.0/connection.js" type="text/javascript"></script>
    <script src="https://code.jquery.com/ui/1.9.0/jquery-ui.js"></script>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css"/>
    <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.
            apexAccountList.push('{!accList.name}');
        </apex:repeat>
        
        //We will establish a connection salesforce database using the sforce.connection.init(sessionID, ServerURL) function.
        var sid = '{!$Api.Session_ID}';
        var server = "https://" + window.location.host + "/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.
        for(i=0;i<records.length;i++){
            javascriptContactList[i]=records[i].Name;
        }
        //on Document ready
        j$(document).ready(function(){
            
            j$("#apexaccountautocomplete").autocomplete({
                source : apexAccountList
            });
            j$("#sfjscontactautocomplete").autocomplete({
                source : javascriptContactList
            });
        });
    </script>
    
    <apex:form>
        <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"/>
    </apex:form>
    
</apex:page>

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.

autoComplete
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.

<apex:page>
	<!--Make sure you have the Javascript in the same order that I have listed below.-->
	<script src="https://code.jquery.com/jquery-1.8.2.js"></script>
	<script src="https://code.jquery.com/ui/1.9.0/jquery-ui.js"></script>
	<link rel="stylesheet" href="https://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css"/>
	<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
		j$(document).ready(function(){
			j$("#countryautocomplete").autocomplete({
				source : countryArray
			});
		});
	</script>
	<apex:form>
		<b>Enter Text</b><input type="text" id="countryautocomplete"/>
	</apex:form>
</apex:page>

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’.