Category: Salesforce

How to read cookies set by JavaScript in a Salesforce Apex Class

How to read cookies set by JavaScript in a Salesforce Apex Class

I recently had a requirement to have JavaScript create a cookie and then read it in later by an Apex class. You would think you could simply create a cookie in JavaScript and then read it in Apex using the exact same name as the cookie, but that’s not exactly the case.

Cookies that need to be read by an Apex Class need to start with apex__ or they won’t be readable by Apex. One other thing to keep in mind is that if apex changes the cookies values they will be url encoded. For example, the @ symbol will have it’s value changed to the percentage sign and the hexadecimal version.

For this example, we’re assuming you want to set a cookie called “settings” to true as soon as the javascript loads. I’m using a standard pattern I’ve documented previously about using jQuery in Visualforce.


function j$(function() {

function setCookie(cookieName, value){
    var cookieString = cookieName + "=" + value;
    document.cookie = cookieString;

To access the values in apex, we would probably have some sort of functions like the below examples.

 	private string savedSettings = null;
 	public PageReference OnLoad()
 		savedSettings = getCookie('settings');

// Private method used to set the cookie value
	private void setCookieString(String cookieName, String value)
		Cookie ck = ApexPages.currentPage().getCookies().get(cookieName);
		ck = new Cookie(cookieName, String.valueOf(value),null,-1,false);
		ApexPages.currentPage().setCookies(new Cookie[]{ck});
	// Private method used to retrieve the cookie value
	private String getCookie(String cookieName)
		Cookie ck = ApexPages.currentPage().getCookies().get(cookieName);
	    return ck != null ? ck.getValue() : '';

Apex: How to Dynamically Tell if a Salesforce Field Exists

How to Dynamically Tell if a Salesforce Field Exists

Lately, I’ve been working on a lot of dynamic apex and soql. I had a requirement to develop a custom appexchange app that could be dynamically querying objects based on a mapping that the admin had supplied and had stored in custom settings.

Originally, I was querying to see if the field existed and returning true if a result was received but this ended taking a lot longer than doing a describe.

I wasn’t able to find any information on how to really tell if a field exists or not. Without further ado, doesFieldExist will return true if the object and field both exist. If the object has been removed and the code hasn’t caught that it will also return false. And finally, if the object exists but the field doesn’t it will return false.

public boolean doesFieldExist(String objName, string fieldName)
    	try {
    		SObject so = Schema.getGlobalDescribe().get(objName).newSObject();
    		return so.getSobjectType().getDescribe().fields.getMap().containsKey(fieldName);
    	catch(Exception ex) {}
    	return false;

How to have a Visualforce Page Download as a pdf

Salesforce Logo

When creating applications it’s a pretty common request to be able to create a formatted report or file in pdf file format.

For the most part, most customized pages and data can be easily converted into a PDF file without having to make many changes. In Salesforce, we can change customized Visualforce pages to create a pdf file by using the renderAs property and set the value to pdf.

Continue reading

Using jQuery in Visualforce

jQuery Logo

jQuery is one of the most utilized JavaScript libraries and can be easily be integrated into any visualforce page regardless of whether it’s meant for your internal users or on a site. jQuery is usually used for manipulating elements in the DOM, animation or even event handling. Usually, I use it for doing some in page validation on form fields, so that we don’t have to post back to the server to find out if something is valid or not.

Before jQuery can be used in the visualforce page, it needs to be referenced. I recommend using the script hosted on a CDN by either jQuery or google or Microsoft. If you are interested in using Google’s, you can find it on the google developers site.

Here’s how to include it in the page (if using Google’s CDN):

<apex:includeScript value=" />

If you decide to host jQuery yourself, you’ll need to do something like the following. Your value could be different, I’m assuming you’ve uploaded into a static resource called “” which has jQuery named as jQuery.js.

<apex:includeScript value="{!URLFOR($Resource.scripts, '/jQuery.js')}" />

After including jQuery, we need to put jQuery in no conflict mode because Salesforce uses Prototype and references the $ sign. Usually, I assign j$ to be used instead of simply typing jQuery instead of $.

<script> j$ = jQuery.noConflict(); </script>

And now, whenever you want to use jQuery in the javascript in your visualforce page you will need to use j$ instead.

Here’s an example of how to do it:

j$(function() { doSomething(); });

instead of

$(function() { doSomething(); }

Note: it’s best to avoid duplicating code in each page, so consider doing this in a custom visualforce component or using a visualforce master page.

And finally, always set an id or class on any element that you would want to reference in javascript. The engine that converts visualforce components into actual html mangles the ids quite a bit. It’s easiest to make use of the attribute ends with method because the managled ids contain special characters that need to be escaped.

Example Element:

<apex:inputText value="{!account.Name}" id="acc_Name" />

To reference the example element, you would then need to do the following:


Hope this helps!

Apex How to Get a List of Fields Set on an sObject

I recently had a requirement to dynamically determine what fields had been set or queried on a sObject, so that a comparison could be done on what was actually stored in Salesforce’s Datastore.

Surprisingly, there’s no way method on the sObject that let’s you tell what’s actually been queried or set. So without further ado, here’s the method that I decided to use because it’s much faster than doing a describe and catching every exception.

public class Utils {
	//Takes in an sObject and determines what values have been queried or set on the page.
	public static Set<String> getFieldsSet(sObject obj)
		if (obj == null)
			return new Set<String>();
		Map<String, Object> fieldValues = (Map<String, Object>) JSON.deserializeUntyped(JSON.serialize(obj));
		if (fieldValues.containsKey('attributes'))
		return fieldValues.keySet();


Security in Salesforce

Salesforce Logo

Salesforce has quite a bit of built in security; and has lots of security features that can be customized. Access to most parts of the Salesforce / platform isn’t actually available until a user has been authenticated.

A few weeks ago, I began studying for Admin Certifications, and was fortunate to find this photo on twitter that @SalesforceBen had shared.

Security in Salesforce House

Security in Salesforce can basically be broken up into profiles and roles. Although they sound pretty similar, profiles and roles do have some differences. Profiles determine record privileges, and determine what the user can do. Profiles also control some salesforce system privileges. Roles or “Role Hierarchy” allows the user to access subordinate’s records, but doesn’t allow upward access.

While Salesforce has a lot of built in security, there’s still some of the standard risks such as Cross Site Scripting (XSS), Cross-Site Request Forgery (CSRF), and SQL Injection (SOQL Injection). The Salesforce Security Guide can help reduce some of these risks.

Book Review: Practical Development Without Code

Practical Development Without Code

Practical Development Without Code written by Phil Weinmeister has been recently released. I think the book really targets those new to the Salesforce platform and does a wonderful job of providing examples and providing a reference that will be useful in the future.

Phil Weinmeister has done a phenomenal job putting together some different scenarios where it makes absolute sense to make use of the declarative functionality that Salesforce provides. As a developer I’ve struggled quite a bit when to use “clicks not code” and feel that Phil has great examples that would be useful to most Salesforce Admins and developers to learn from.

Some of the topics covered include workflows, approvals, process builder, validation rules, and more.

The chapter on object and field level permissions in Salesforce is really well written. I really wish this book had existed when I was first starting to use Salesforce.

Overall, I recommend using the book to learn the declarative features of Salesforce.

How to use Bootstrap In Visualforce

Bootstrap Logo

Bootstrap is a free and really popular open source CSS framework that works pretty well for designing responsive websites and web applications. Under the hood, it’s a giant collection of handy reusable bits of code written in HTML, CSS and JavaScript.

By incorporating Bootstrap into Visualforce pages we are able to some pretty good looking websites. Bootstrap and Visualforce can work very well together allowing us to accomplish a lot. For example, the eWAY Merchant Application is built with Visualforce, Bootstrap and jQuery.

Step one is to download Bootstrap from their website located at and simply click the “Download” button.

After you have downloaded the zip, you can simply upload it into the static resources and use it in our html in a secure and consistent way. Assuming you have uploaded a zip file called “” we could reference it in our pages like this.

<apex:includeScript value="{!URLFOR($Resource.scripts, '/bootstrap.min.js')}"  />

Depending on how we intend to use it, ie is it internal visualforce pages or is it external visualforce pages we might need to do things slightly differently.

Using it For Internal Salesforce Pages

If you are intending to use bootstrap on internal pages you will probably need to customize the CSS for bootstrap because Salesforce’s stylesheets don’t play all that well with it.

CSS works in a global scope, so any time we use Salesforce’s headers (aka Salesforce’s style.css) there will be clashes. We can solve that by doing the following:

  1. Unzipping the bootstrap zip that we downloaded above.
  2. Opening up the bootstrap.scss and wrapping the entire whole with a custom named class. I tend to think I’m pretty pragmatic so I use things like .bootstrap
  3. Compile a new css file.
  4. Whenever we want to use Bootstrap we simply wrap all of the components in a div like this <div class=”bootstrap”>AllMyAwesomeHTML</div>.
  5. Upload all the bootstrap goodies to static resources and reference them in pages.

For a more detailed breakdown see Chris Youderian’s post called “How to Isolate Bootstrap CSS To Avoid Conflicts“.

Using Bootstrap In External Salesforce Pages

For external facing pages that don’t need any of the Salesforce UI you can simply turn off the tabs, header, and side like this:

<apex:page standardStylesheets="false" showHeader="false" sidebar="false" >


This works pretty well when the page isn’t intended for internal data entry or when we really need Salesforce’s styling.

I also recommend considering setting applyHTMLTag to false so we can insert our own html, head, and body tags. Setting the docType to “html-5.0” can make this a lot more pleasant experience.

Introduction to Testing in Salesforce

Automated testing confirms whether a piece of particular code is working correctly. And, its no secret, that writing automated tests helps decrease bugs and locate existing bugs.

Why write test methods?

  1. Test Methods are required to deploy Apex to a production environment. In Salesforce, all classes must have at least 75% code coverage.
  2. If you are releasing an app onto Salesforce’s AppExchange they are required.
  3. Test methods provide test automation which can enable greater QA efficiency, and can help avoid creating future bugs in the maintenance stage.
  4. They provide a very easy way of doing automated regression testing.

Within the development community there are a lot of debates about how much testing is required.

Types of Tests
Unit Tests test the least lines of code; but reduce external dependencies by using mock objects.

Unit Tests can be really challenging to implement in really interconnected code bases.

Integration Testing covers how the different “units” interact together.

Functional Tests

Some Best Practices

  • Don’t Depend on Pre-Existing Data
  • use System.runAs() methods to verify test users can find records that were shared with apex
  • Mimic VisualForce page interactions by explicity calling methods

Salesforce Quick Deploy

Releasing changes from a sandbox into production Salesforce can be an interesting time as a developer.

As your instance gains more and more code, and tests, the amount of time it takes for changes to deploy increases.

Quick deploy is a relatively new feature that can deploy components up to 96 hours after they have been validated. This can be incredibly handy, if you are needing to deploy changes that may cause a temporary service interruption or invalidate a page’s viewstate.

My personal favourite use is starting the validation at the end of the day and then being able to deploy first thing.

Salesforce Spring15 Test Class Additions

Salesforce has finally introduced a way to create test data for an entire test class; this will be a huge time savings for developers.

The rollback of records created during execution happens at the end of the test class’ execution. By only inserting records once, we should see tests run faster and require less system resources.

Lately, I have been updating all of my test classes to use this new @testSetup annotation. One thing to keep in mind, is that it will not set static variables and has a bug for package developers.

Here’s some sample code:

private class join_Controller_Test {

	@TestSetup static void CreateTestData() {
		Account acc = Util_TestSetup.createAccount();

	static testMethod void Test_Load() {

		Account acc = [select Id from Account];

                PageReference p = new PageReference('apex/internal_join');
                p.getParameters().put('acc', acc.Id);


                internalJoin_Controller controller = new internalJoin_Controller();
		system.assertEquals(null, controller.OnLoad() );
		system.assertNotEquals(null, controller.acc );


I hope that the addition of @testSetup will finally result in better tests on Salesforce. As most programmers with test experience know, testing in Salesforce isn’t usually true unit testing.

Most are usually coded to be integration tests instead. Unit tests are tests that written to verify small sections (“units”) of code; integration testing is testing how the different units work together.

Another common, and disturbing trend, is that most programmers are simply coding unit tests to just get the 75% coverage and not using asserts. By using asserts, the tests can help significantly reduce bugs before code leaves development.

Introduction to Salesforce Trailhead

When Salesforce introduced Trailhead in the Dreamforce 2014 Developer Keynote I wasn’t overly excited. Trailhead is Salesforce’s Learning Platform; it’s designed to teach you how to administer and program in

Over the last few months, it’s really started to come together and offer lots of interesting content, and challenges.


Trailhead consists of three different trails (or streams) that cover different parts of the platform. The trails are then split into modules which take anywhere from a few minutes to about an hour to read and complete the challenge.

Trailhead Streams

Each module has examples, videos, and follow up exercises. The follow up exercise is often a multiple answer quiz or doing some sort of task through the platform.

To work on the system you need to have a salesforce developer community account, and then login. For each challenge you will be asked to link a Developer Edition account. This process is relatively seamless and simple.

I strongly recommend using a new developer edition account as it will break some challenges if you have different permission sets and validation rules. Error messages provided are incredibly generic and don’t usually seem to exist with a new developer edition account.


As you can see from the above photo of the trails, they are split into basically three distinct sections of The first trail or “Getting Started with the Platform” covers the basics of security, creating a custom app, and creating a custom object. The section about security is incredible well written and I believe we all have the potential to learn something there.


Salesforce has cleverly built gamification into Trailed by giving out points for completing challenges. Once you have completed a trail you receive a badge. which is visible on your public Developer Community Profile for all of the world to see. 🙂

What’s really great about the challenges is that they aren’t just about coding or “declarative programming”, but there’s also some different tasks with configuration.

The data security trail covers a lot of different configuration options with profiles and permission sets.

Making the Most of Salesforce Trailhead

  • Read the text on the page, and Watch the videos. Some of the videos include information that isn’t really included in the text on the page.
  • Do the practice exercises. Most of these exercises only take a few minutes.
  • Look at the related resources.These resources mentioned at the end of many units are useful.
  • Celebrate your successes and failures; this is part of the learning process. We only can get better by doing. Post on twitter or Facebook when you’ve succeeded.


I believe Salesforce Trailhead is worth trying, and I’m sure even the seasoned expert can learn something as SFDC sure is a huge system. Salesforce seems to be adding new modules to the trails as newer features are being added; for example, there’s now a module regarding lightning/aura.

Hopefully they continue to keep adding to Trailhead, so we can learn about new features right around the time they are available in the new releases.

Happy hiking!

How to Make the apex:pageblocksection header collapsible

Since I’ve started developing for Salesforce one thing that has always frustrated me is that the apex:pageBlockSection’s header wasn’t collapsing the section when it was clicked. In this post, I’ve provided example code that will allow you to make headers collapsible when clicked by the user.

By adding the below JavaScript, we can easily add the collapsing to the headers. Make sure to include jQuery, and to add this code to your onload function. If you aren’t sure how to include jQuery please read my article on how to include jQuery in visualforce.

//Makes apex:pageBlockSection whole header clickable instead of that little ridiculous arrow.
jQuery('.tertiaryPalette').click(function() {
var eId = jQuery(this).parent().attr('id');

if (eId != null &amp;&amp; eId != '')

//we need to readd the click event to the little arrow image; or some users may be confused.
jQuery('.tertiaryPalette img').click(function() {
var eId = jQuery(this).parent().parent().attr('id');

if (eId != null &amp;&amp; eId != '') {

Salesforce Spring15 Including Mapping Features

Salesforce’s Spring 15 release is going to include mapping and geolocation for address fields. I believe, location based features started appearing before I started using Salesforce.

Even more exciting, is that visualforce will include a map component. The mapping component appears to be using Google Maps, but this could probably change.

The new mapping component uses JavaScript to zoom, and move around.

If you get an error when including the maps that reads something like this: “visualforce maps are not enabled for your organization. please contact your administrator” you will need to enable them by following the below directions.

How to Enable in Pre-Release
Setup -> Build -> Customize -> Maps & Location -> Settings. Read the disclaimer and click Okay or Agree.

Including the Map in Visualforce is incredibly easy; it can be done in basically one line of code. The component is simply apex:map.

If you get an error when trying to save the page, make sure your page version is at least 32.

How to do Callouts from Apex Triggers

Salesforce Logo

In this blog post, we’ll discuss how to correctly do Callouts from Apex Triggers. Salesforce doesn’t allow External Callouts to directly happen from Apex Triggers. You will get the error “Callout from triggers are currently not supported’.

Continue reading

Dreamforce 2014 Notes: Write Apex Tests Using Best Practices

One of the hands on training sessions I attended was “Write Apex Tests Using Best Practices” which really proved to me that a lot of what I believed and was doing were right.

Without further ado, here’s my notes:

Goals for tests

  • Auomated methods that verify application integrity
  • Future Proof
  • Proactively Identify Problems before they enter production
  • Salesforce Runs all customer tests before updates
  • Postive tests & Negative tests
  • Classes that are demarcated by the @isTest annontation won’t count against Apex code limit
  • contain member methods that can only be contained & used in a test
  • tests always have a void return type & no params
  • tests are always static
  • single autonomous transaction
  • only heap space, governor, etc
  • tests should insert their own test data
  • tests should be able to handle uncaught exceptions, etc
  • tests should have assertions to determine validity

Tests Leave No Footprint

  • Apex tests will not commit changes. SOQL still finds records
  • will not performs callouts to external web services
  • will not send outbound email


Tests Expect to Work with Mock Data

  • static resources can be used to stage test data in a cache
  • SOSL searches will not find pre-existing records
  • SOQL queries will only find pre-existing records for the following objects:
    • User
    • Profile
    • Organization
    • RecordType
    • For all other objects, SOQL visibility may be overridden with @isTest(seeAllData=true)


  • verify code is bulk ready
  • pass up to 200 records

Verify End State

  • using assertions

Best Practices

Don’t Depend on Pre-Existing Data

  • Avoid SOQL to initalize SOQL using SeeAllData=true
    • less portable
    • inconsistent results
  • Utilize mock data
  • Call Test.loadData() in a test method to populate
  • Create reusable mock data factories
  • Triggers should never contain business logic, they should only contain calls to classes
  • Use a Naming Convention like NameOfClass_Test
  • Exclude mock data initialization and result verification actions from governor calculations
  • Create separate tests with narrow goals


  • blue boxes: test logic
  • grey boxes: business logic

Testing Visualforce Controllers

  • Mimic VisualForce page interactions by explicity calling methods
    • Form fields, eg form.Name use getter/setters
  • Test controller extensions by mocking the controller that was extended


Test.startTest synchronously runs asynchronous Apex

Testing Callouts

  • developers need to implement mock calls and responses that do not access the web services
  • setMock() needs to be run to do the fake response and call out

Testing Record Access

  • use System.runAs() methods to verify test users can find records that were shared with apex
  • using System.runAs() is a best practice.

Dreamforce 2014 Notes: Writing Apex and Visualforce Using Re-usable Patterns

Why use patterns:

  • patterns help us be more efficient
  • patterns describe reusable solutions to common problems

Bulk Processing

  • Caching
  • create triggers w/ ability to process hundreds of lookups
  • challenge: queries, DML, memory
  • collect all keys from trigger object in Set Object
  • Query once using SOQL in clause with key set
  • cache results in map object
  • look up related values using map key

Apex Summary Rollup

  • Need to roll up from a child to a parent in a lookup relationship
  • No declarative option for rolling up in a lookup relationship
  • Identify parent IDs affected by change in child.
  • perform an aggregate query on child records
  • update parents using IDs

Configuration Abstraction

  • Manage values that change from environment to environment
  • Maintainability
  • Ease of use


  • display records one page at a time
  • performance and maintainability
  • StandardSetController

Search And Sort

  • Allows users to apply search criteria and column sort
  • challenges: Performance and maintainability
  • reusuable Apex and component framework for Search and Sort
  • Dynamic SOQL to modify Where and Order by query clauses

Looking Back at Dreamforce 2014

Welcome to DreamforceI was really blessed to be able to attend Dreamforce and learn even more about Salesforce.

While attending there, I attended a lot of the different keynotes and saw a lot of the new exciting features in action.

Dreamforce Sessions

At Dreamforce there was dozens of interesting sounding sessions. There were a few different ones that really stood out to me and offered interesting and new material to me. I believe that a lot of the sessions were recorded and able to viewed at a later date which is really exciting and available on youtube here.

One of my favourite sessions was Advanced Development using Apex Design Patterns by Robert Nunemaker. The vide is one if the hundreds uploaded by Salesforce to youtube here.

New Product Announcements

Before attending Dreamforce, I didn’t realize that Salesforce made a lot of its new product announcements there. Some of the new products they announced were: Lightning Components, Process Builder, Salesforce Wave,

Wave / Analytic Cloud

By Far, Wave was the most interesting announcement at Dreamforce 2014. It is a fairly dynamic business intelligence product that is optimized for use on mobile devices. What’s most awesome about Wave is that it will allow for on the spot and completely interactive exploration by business users rather than the static generated reports that have been prewritten.

Duplication Prevention

Through the use of fuzzy logic and other logic it will now be possible to stop duplication from occurring within Salesforce.

Sale Reach

Sales Reach units the power of Pardot, Communities and Sales Cloud into one system. Apparently, it will be able to do popup notifications on the Salesforce1 Application and assist with Leads/Prospect Tracking.


Lightning is all about reducing development time and code. Lightning is basically a component framework and new set of tools that make building apps and making automation much faster.

Lightning Components allow developers to create reusable components for use in building apps. Lightning seems to be an event-driven architecture that makes use primarily of JavaScript and model-view controller architecture.

Process Builder allows business processes to be automated more easily and in a visual way.

Lightning Connect is the ability to connect to external data sources and with point and click be able to incorporate the data into Salesforce. The basic idea is that gone are the days of legacy systems and data silos, it would now be possible to use this data in Salesforce and with Wave.

Service Cloud

Smart Agent Console is designed to make it easier to provide good customer service to customers by making searching more intelligent, and where applicable making it possible to show sales data and billing data. It’s no secret that more competent agents allows companies to offer better service with less agents, reducing their service costs.

Community Cloud

Community Designer offers a few different themes that out of the box allow businesses to better connect to customers and reduce support costs. Community Designer allows new communities to be deployed by writing no-code and using point and click.

Topics allow users to access all of the relevant information in one place and even follow it to always stay up to date.

I’m so excited for Dreamforce 2015 and can’t wait to go.