Visualforce Dispatcher Page

Sometimes, you might have a requirement that can’t be met using standard page layouts and you need to turn to Visualforce. But, maybe only a subset of the records need to use a Visualforce page and you’d prefer the others to stay using standard page layouts. The solution here is to use a Visualforce dispatcher page that redirects the user to the correct page depending on the criteria you set. There are several good posts about using a dispatcher page to redirect the user to different pages depending on specific criteria, including a classic from Jeff Douglas.

I haven’t seen a post that covers how to handle passing parameters from one page to the next. For example, if you are creating a child record from a related list, the new page prefills in the parent record values through the use of URL parameters. If you have a dispatcher page redirecting users, then the parameters can get dropped and your users don’t have as smooth of an entry process. Here’s a way to redirect and keep all the parameters.  I ran into a few oddities when implementing this. Hopefully the code below helps.

Using Developer Console to Troubleshoot Code

Confessional time: my org is a mess. There have been way too many developers in it and over time it has become a giant pile of triggers and code. It can be a bit intimidating to clean up, but the developer console can help. In this post I’ll show how I use some of the features of the dev console to find where my code can be improved.

One of my tests recently stopped working due to the dreaded “Too many SOQL queries” error. I was able to find the offending SOQL statements with the help of the developer console.

First, open up the console so logging will be captured. In Salesforce, perform that action to replicate the problem or execute the code you want to look at. You should see the log appear in the Logs list. Open the log and switch perspective to Analysis (Debug > Switch Perspective > Analysis(Predefined). This perspective gives you tons of information.

I’m interested in the Executed Units tab under Execution Overview. Since I know I have a problem with my queries, I click on all the buttons except for Queries to make only Queries visible. This gives us a list of all the queries executed. Immediately, I can see a few queries that were executed 16 times! Uh oh. Looks like I have some code that can be optimized. With my new knowledge, I can work towards making my code bulk friendly.

analysis perspective


Take some time to poke around in the perspectives. It really gives you insight into how your code is executing. Happy spelunking!

Yet Another Test Factory

When writing unit tests, it is best practice to centralize the creation of all your test data. While there are a lot of examples of ways to do that on the web (SmartFactory ), I’ve never been completely satisfied with them. SmartFactory is great if you want to be sure you have data in all your fields, but since I know my org and what the data should look like, I prefer to specify field values. Some of the problems I wanted to solve:

  • Minimize number of code statements executed (SmartFactory makes debug logs huge).
  • Have different object templates for various scenarios.
  • Be able to override values for specific one-offs tests.

You can find the code on Github in my Salesforce-Smart-Factory repository. Here’s how you can use it.

// To create an object, just pass an instance of the new object to the method.
// The TestFactory will pre-fill all the fields we typically need
Account a = (Account)TestFactory.createSObject(new Account());
insert a;
// You can also set values to be used. Any values set in the constructor will override the defaults
Opportunity o = (Opportunity)TestFactory.createSObject(new Opportunity(AccountId = a.Id));
// You can also specify a specific set of overrides for different scenarios
Account a = (Account)TestFactory.createSObject(new Account(), 'TestFactory.AccountDefaults');
// Finally, get a bunch of records for testing bulk
Account[] aList = (Account[])TestFactory.createSObjectList(new Account(), 200);

The Salesforce Tribe

I had the fantastic experience of being interviewed by Mike Gerholdt and Jared Miller for the ButtonClick Admin Podcast recently. We had a great time and I really appreciated how insightful both Mike and Jared were about my ramblings. I think the biggest theme we uncovered is that you should do what you love. I love working for a company that I believe in and that is making a difference in people’s lives.  I also love making the mundane parts of people’s jobs automated so they can focus on adding value and making a difference themselves. But, one of the things that makes me really enjoy what I do is the Salesforce community.

Over the last year or so, I kept running across the idea of a tribe. And I truly believe that’s what we, the Salesforce community, are.

A tribe is a group of people connected to one another, connected to a leader, and connected to an idea. For millions of years, human beings have been part of one tribe or another. A group needs only two things to be a tribe: a shared interest and a way to communicate. – Seth Godin, Tribes: We Need You to Lead Us

Our shared interest could be Salesforce, but I think that isn’t quite right. Our shared interest is in making it easier to work. Salesforce is just the tool we’ve all found that not only works well for our users, but also makes it easy for us to do our jobs. We have many communication channels that I outlined in my post Getting the Most from the Salesforce Community. We have leaders like Jared, Mike, and all the other Salesforce MVPs.

This American Life had an episode on tribes last year that resonated with me. One of my favorite quotes was in the prologue about how each tribe has ways of identifying true members.

If I come into a group and I say, I’m really a long-lost member of your group but I can’t speak your language and I haven’t tattooed myself. Then it’ll immediately be obvious that I’m not a member of your group. So all groups have what are called “expensive” ways of identifying themselves honestly so that you can’t just fake it. – Jared Diamond

So, become an authentic member of our tribe. Contribute to the community. You will be rewarded.

Continuous Integration Using

As mentioned in my previous post, Team Development on, Continuous Integration is a key part of getting your team to working efficiently. I recently found to be really easy to get setup. They provide a trial with 50 free builds. After that, the cheapest option is $25/month for unlimited builds. I was using it in a matter of minutes after signing up for an account. In this post, I’ll describe how to setup to build your Git branch into a target org.

First we need a repository in Git. works really well with both Github and Bitbucket. I’ve set up a  demo repo on Bitbucket that you can fork and use to try it out. (This repo will deploy a custom object called Test1__c to your target org.) First, let’s look at the things that aren’t usually in Salesforce metadata. At the root directory, you’ll see three new items:

  • lib folder that contains the ant-salesforce.jar – this provides the Ant files needed to deploy to Salesforce.
  • – this provides some settings for the deploy
  • build.xml – this provides the deploy actions we can use to deploy to the target org.

Let’s look a little deeper at the two build files.


This file sets up the deploy targets. Provided are two targets, one runs all tests and the other runs none. You’ll notice there are several variables in use in the file including sf.username. This allows us to avoid hardcoding values and also prevents them from being visible in source control.  We’ll use these later in our setup.

<project name="ci-demo" default="test" basedir="." xmlns:sf="antlib:com.salesforce">

    <property file=""/>
    <property environment="env"/>

    <target name="deployRunAllTests">
      <sf:deploy username="${sf.username}" 
        maxPoll="${sf.maxPoll}" />

    <target name="deployRunNoTests">
      <sf:deploy username="${sf.username}" 
        maxPoll="${sf.maxPoll}" />


This file provides some of the default values for the build. In this case, the default server url is so I can deploy to a developer org. Change this  to to deploy to a sandbox org. The other variable I tend to tweak is the maxPoll. The default is 20 and I find for large deploys this isn’t near enough time to let the deploy finish.

sf.serverurl =
sf.maxPoll = 100

With our repo all set up and pushed to Bitbucket, we are ready to set up the build job. First create an account at You can use your Bitbucket credentials, which makes things pretty convenient later on. After you have your account created, click on “New Project” at the top of the page, select Bitbucket, then pick your repo. You’ll then be prompted to select a language. I just went with Java as that has all the components we need. In the script window, enter the following command:

ant -lib lib/ant-salesforce.jar -Dsf.username=${SFUSER} -Dsf.password=${SFPWD} deployRunNoTests

This invokes Ant and tells it to include the ant-salesforce.jar. It then sets the username and password using an environment variable (I’ll cover that in a minute) and finally tells Ant to use the deployRunNoTests target in the build.xml file.

After saving the script, let’s add the username and password environment variables. I use variables here so the password is not transmitted in clear text when success and failure emails are sent.

[email protected]

With everything entered, click Save at the bottom of the page and then click Build Now at the top of the page. You’ll see a bunch of messages display and hopefully something like this:
deploy log


You now have a project setup! It will automatically build every time you commit to Bitbucket. If you use branches, you should go to the project settings and enter in only the branches you want to trigger builds. You can even get fancy and have the build do different things depending on the branch being committed. Here’s an example where we have two different branches. When the branch called develop is committed, we don’t run all tests. When master is committed, we run all tests. You could also have develop build to one org and master to another by changing the username and passwords being used.

[ $DRONE_BRANCH == “develop” ] && ant -lib lib/ant-salesforce.jar -Dsf.username=${SFUSER} -Dsf.password=${SFPWD} deployRunNoTests
[ $DRONE_BRANCH == “master” ] && ant -lib lib/ant-salesforce.jar -Dsf.username=${SFUSER} -Dsf.password=${SFPWD} deployRunAllTests

Poke around at the other settings. If you find other tricks, let me know what you like to do. Happy developing!

Team Development on

One of the challenges of working with a team of developers is managing the changes everyone is making and not have one developer overwrite the changes another one makes. In this post, I’ll describe the setup I’ve found to work. I’ll be writing followup posts with more detail describing exactly how I use some of these tools. All tools described work on both Windows and Mac.

1. One developer per sandbox

Each developer should get their own sandbox or developer edition to work in. All changes should be made in their sandbox. This prevents a developer from making a change to a class in their IDE which hasn’t been refreshed recently overwriting a change another developer did recently.

2. Sublime Text with Mavensmate

The combination of Sublime Text with the MavensMate plugin is really powerful. MavensMate makes it easy to retrieve metadata from Salesforce and saving is super quick compared to the Eclipse IDE. I never want to open Eclipse again.

3. Use Source Control to Track Changes

I prefer to use Git because that’s what all the cool kids seem to be using and the tools out there are fantastic. I use Bitbucket because they provide free private repositories for up to 5 developers. The nice thing is there are many options out there that are free/low cost and you don’t have to install a server locally. I like to use the free SourceTree client because I can never remember the git commands. It also lets me more easily see the changes I’m about to commit. As each developer works, they should be working on their own branch and then merging their changes into the master branch as they are finished.  I can’t tell you how many times I’ve used source control to go back and see the changes done. In one situation, a change caused major issues, I was able to go back, reverse the commit, and we were back in business really quickly. When a developer needs to bring their sandbox back in sync with the master branch, they can use the Migration Tool to deploy all the changes back into the org.

4. Use a CI Tool to Build to a Staging Sandbox

Now that you’ve got everything merged into source control, you need an org to test everything in. You could have each developer deploy their changes manually to a staging org, but I prefer to use a Continuous Integration tool to do it for me. I recently found and it is really easy to setup to automate the deploy of all metadata to your staging org. adds hooks to Bitbucket so when a change is committed to the repository, it automatically begins a build using the migration tool. You can get emails on successes and failures. The one drawback is that there isn’t a way to deploy destructive changes automatically. Any deletion of objects, classes, pages, etc need to be done by hand.

I hope this description of my environment helps you get your team up and working peacefully together!



Using Regex to Parse Text Fields

Regular Expressions always seems very complicated, but they can elegantly solve some complicated problems. I had an interesting problem where I needed to find some text that matched a pattern in a text field and pull it out. I ended up turning to using a regex matcher to find the information I needed.

The hardest part of regex is coming up with the correct pattern. One site that can help with this is This site lets you enter sample text and it gives you regular expressions matching certain parts of it.

In this example, I’m looking for a date that is prefixed by the text “Completion Date:”. My date will always be in the MM/DD/YYYY format, so my pattern is pretty simple. I declare a pattern and a matcher and then loop through all the matches and output them to the debug log.

String DATE_PATTERN = 'Completion Date:(\\d{1,2}/\\d{1,2}/\\d{4})';
Pattern p = Pattern.compile(DATE_PATTERN);
Matcher pm = p.matcher('Some text, more text. Completion Date:11/15/2012 even more' +
                         'text Completion Date:5/6/2012');
while (pm.find()) {

While this is a pretty simple example, it shows how you can avoid doing searches, finding indexes and performing substring operations in text fields.

More Chatter Mobile Features

While I’m still excited about Visualforce pages in Chatter Mobile, I was able to dive into more of the features in Chatter Mobile and they are great! Below you’ll find some details about other features I really like:

Compact Layouts are used in a number of places in Chatter Mobile. These include the detail page for a record and enhanced lookups (more on those next). You can have multiple compact layouts per object and assign them to different record types. To edit your compact layouts, navigate to Setup>Customize>Object>Compact Layouts. After creating a layout, make sure to assign it to a record type. The first place you’ll see the change is at the top of the detail page.

compact layout


You can then edit the page layout and add expanded layouts lookups to other objects. These add cards to the mobile view and use the same compact layout.

expanded lookups

The recent items for each object has several improvements. Notice the New button to allow you to create new records easily. List views you’ve used recently can be accessed from this page as well. These are displayed as cards that look similar to the compact layouts but the data in them is determined by the columns selected in the list view.

recent accounts


Finally, I also really like the integration with your phone’s calendar. Use the Today app in Chatter Mobile and it shows you all your meetings and if it matches up attendees with Salesforce contacts, you can see their contact details.

What are your digging about the latest version of Chatter Mobile? How will it help your users be more productive on the move?

Chatter Mobile and Visualforce

Salesforce’s mobile offering keeps getting stronger with the run up to Dreamforce. Last night the latest version of Chatter Mobile for iOS hit the app store and it sounds like the Android one is hot on its heels. It is chock full of features, but the one that caught my eye immediately was that we can now include Visualforce in the app.

First, we need a Visualforce page that is already mobile-ready. Fortunately, I already had some in my demo org thanks to Reid Carlberg’s Javascript Playground. Install the unmanaged package into a dev org and you’ll see it includes several VF pages that work well in mobile browsers. The one I’m going to use is the page called LABJS_JQueryMobile130_Hello.

After we have a page, we need to tell Salesforce that the page itself is mobile ready. That is easy to do by navigating to Develop>Pages, editing the page and checking the box “Available for Salesforce mobile apps”

mobile enabling a VF page

Now, we get to the good stuff. Under Administer>Mobile Administration, you’ll find a new option called Mobile Navigation. This lets us rearrange “stage left” in the Chatter Mobile app. We can add and remove standard components and also add our mobile enabled Visualforce tabs here.

mobile navigation


With everything in place, you should be able to open Chatter Mobile, see your tab in the stage left menu and select it:

stageleft  vftab

And that’s all there is to getting Visualforce pages in Chatter Mobile. Have fun hacking!

Update: In my original post, I had stated that you also need to mark the tab as mobile ready. That isn’t needed so the post has been updated.

Change Sets and Profile Permissions

Did you know your change sets may be including more permission changes than you thought? I recently deployed a new field in a change set along with the “profile settings for for included components”. I selected all the profiles in my org because I wanted to make sure all my profiles could see the new field. After deploying, I discovered that the change set deploy had removed one of the login IP ranges for a profile. Turns out that is expected behavior as described in the help.

This behavior was unexpected to me and didn’t seem right, so I started asking around and was able to talk to the PM for Change Sets, Andrew Smith. We had a great talk about change sets and I learned a thing or two that I thought would be nice to share with others.

First, change sets will modify many profile settings when you include them in the “profile settings for for included components” section. Not only will it give appropriate permissions for things such as fields, but it will also overwrite login IP ranges among other things. (Take a look at this help doc for the entire list.) In Winter 14 this list gets expanded and will also include user permissions such as “Manage Users”. I tested this in a couple of Winter ’14 sandboxes and was alarmed to see that the audit trail did not record any of the user permissions changes. The moral of this story is that you need to be sure your profiles in your sandboxes are exactly what you want as the changes will move with the change set.

Second, we discussed that change sets are not typically destructive, but there are certain cases where change sets will remove items:

For instance, we delete picklist values in a field that you migrate.  Same goes for adding/removing workflow actions associated with a rule when you move the rule (the link to the actions – not the actions themselves).  Our general rule is we don’t delete things you can add to a change set directly (think field, object, report), but we will update (including removal) sub aspects of a component as part of migrating that component.

Change sets are a great feature and I’m looking forward to future clarification on what can and can’t get deployed as well as improvements to the UI for selecting items to add to the change set. Tips and Tricks