Salesforce LWC Editor in browser

Salesforce made a great move by making the Web Components part of the eco system by introducing Lightning Web Component(LWC). But for some reason, they decided not to provide the ability to code it directly from their developer console. Currently the only way to do it is, is by using the VS Code. This is great, but if you’re in a hurry and want to make some quick changes, it won’t be easy.

To resolve this, I decided to make a quick-to-use LWC editor in my chrome extension Salesforce Advanced Code Searcher.

How to use:

  1. Install the extension by going to : https://chrome.google.com/webstore/detail/salesforce-advanced-code/lnkgcmpjkkkeffambkllliefdpjdklmi
  2. Navigate to your salesforce setup Page. You should see a “Click here to authorize” button. Click on it to authorize the extension.
Image for post

3. Once the authorization is complete, Navigate to the LWC Editor tab and you should see all the Components that already exists in the Org. In case there are none then you can start by creating one.

Image for post

What can you do?

  1. You can edit the components and save it back.

Look for the extension that you are looking for in the left file explorer, click open the link and that should open the file in a new tab. Make the required changes and hit Ctrl+s (PC) or Cmd +s (Mac) to save the change. In case there are errors it will be displayed in the console log right below the editor.

2. You can add a file in an existing components.

Image for post
Image for post

Right-click on the component where you want to add a file. You will be presented with 2 options : New File & Delete. Click on the New File to open a modal dialog where you can key in the file name (do not add an extension). Click on the Create File button and it will add the file under the component.

3. You can delete the files in the component.

Image for post

5. You can also change the theme:

Image for post

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);