Category Archives: salesforce

How to Dynamically Populate Fields in Salesforce Data Entry Screens Using Apex Classes

I recently had to solve this use case for a work project and I thought I would share as it could be very useful across a number of scenarios within  Salesforce. Why this is really useful and powerful is that it works on a New Object screen BEFORE the save occurs. So you can see results while the screen is still in edit mode.

The application has two custom objects, Proposal and Project, that are related with a lookup from Project to Proposal. While the relationship  is not Master-Detail, the Proposal lookup field is required on the Project screen so that a Proposal is required before a Project can be created.  Both Proposal and Project have fields in common of Title, Account, Contact, and Scope of Work. Title, Account, and Contact are required on both objects.

The Use Case is that when creating a new Project all four of these fields should copy over from the related Proposal so the user doesn’t have to reenter them,  while remaining editable on the Project data entry screen, all before saving the Project. So when the New Project button is clicked, and the related Proposal is selected, all of the related common field values from the Proposal should immediately copy over into matching fields on the Project screen prior to clicking the Project save button.  Workflow field updates and triggers don’t work for this scenario because (1) we don’t want to first have to click save and then go back into edit before making changes and finish filling out other fields on the New Project screen. And (2) since these fields are required on the Project screen the record won’t save in the first place unless all of the required fields contain values.

proposalexample

 

The solution has to work in two different cases when creating a new Project. One is clicking the Project tab and then selecting the New Project button. In this scenario the user will need to first select the related Proposal after which the related fields should be copied over from Proposal to Project. The other case occurs when starting from the Proposal screen and clicking the New Project button in the related project list. In this case the Proposal__c.Name is automatically copied over to the related Proposal__c field on new Project screen and so is unnecessary for the user to select. Our solution has to work correctly for both of these cases.

The solution for this problem is to create a Visualforce page with an extended controller class that replaces the standard New Project page. Three files have to be created to make this work, a Visualforce page,  an Apex class, and a unit test. Salesforce requires you to run a unit test on all code before you are able to deploy from sandbox into production.

The VisualForce Page

I won’t go into how to create a VisualForce page here, but I will mention a free tool I use which makes turning a standard or custom object page into a VisualForce page a snap.  It’s called Layout Page and can be found in the App Store. It converts any Salesforce Page Layout (Standard OR Custom) into a Standard Visualforce Page instantly.

Once you have created the VisualForce page the following changes should be made.

The first line of the VisualForce page shown below sets the controller and extension for the page. The main controller is the Project__c object and the Apex extension class is named RelatedController1.

<apex:page standardController="Project__c" extensions="RelatedController1">

This next line of code calls the Apex function PopulateProject() whenever a user selects the related Proposal. The PopulateProject() method will locate the selected Proposal record in Proposal__c and copy the fields, Title, Contact, Account, and Scope_of_Work from the selected Proposal record into the appropriate fields on the new Project screen. This line handles the scenario where the user selects the New Project button from the Projects tab and so on the New Project screen the related Proposal is blank and needs to be manually selected.

<apex:inputField value="{!Project__c.Proposal__c}">
            <apex:actionSupport event="onchange" action="{!PopulateProject}" rerender="accinfo, msgs"/> 
         </apex:inputField>

The following line handles the scenario where the user selects New Project button from the Project related list on the Proposal screen where the Proposal Name will already be filled in and so not necessary to select. This line calls an inline Ajax function located at the bottom of the VisualForce page that checks to see if the  Project__c.Proposal__c field is NOT null, in which case it calls the Apex method PopulateProject to copy in all of the Proposal field values.

<apex:actionFunction name="CallApexMethod" action="{!PopulateProject}" reRender="accinfo, msgs"/>

The Ajax code below should be located at the bottom of the VisualForce page just above the </apex:page> tag. This script executes on every page load, which is what we need in order to check if the related Proposal has already been selected.

<script>
    function addLoadEvent(func) 
{ 
  var oldonload = window.onload; 
  if (typeof window.onload != 'function') 
  { 
     window.onload = func; 
  } 
  else
  { 
      window.onload = function()  
      { 
        if (oldonload) 
        { 
           oldonload(); 
        } 
        func(); 
      } 
   } 
} 
   
addLoadEvent(function()  
{ 
var controllervariable='{!Project__c.Proposal__c}';
if(controllervariable==null){return false;}
else {
  CallApexMethod(); }
});
</script>

The Apex Class

The Apex class, RelatedController1, is shown below. This where all the work happens to locate the selected Proposal record and set fields in the new Project record equal to fields from the selected Proposal record.

public with sharing class RelatedController1
{
public Proposal__c prop {get;set;}

private ApexPages.StandardController stdCtrl;

public RelatedController1(ApexPages.StandardController std)
{
stdCtrl=std;
}

public void PopulateProject()
{
Project__c proj=(Project__c) stdCtrl.getRecord();
if(proj.Proposal__c == null){return;}
else{
prop=[select Name,  Account__c, Scope_of_Work__c, Contact__c from Proposal__c where Id=:proj.Proposal__c];

proj.Name=prop.Name;
proj.Account__c=prop.Account__c;
proj.Scope_of_Work__c=prop.Scope_of_Work__c;
proj.Project_Contact__c=prop.Contact__c;}
}
}

All of the work described so far has to be completed in a Salesforce sandbox or developer account. I used a  partial sandbox under my Production org which copies a subset of data into the sandbox along with all of the Production org metadata.

The Unit Test

Once everything is working correctly in sandbox, you will have to create a unit test that when run exercises at least 80% of the code in the Apex class without error. Only then will Salesforce allow you to create an outbound change set and deploy it into your Production org.

The code for the test class is shown below.

@isTest(SeeAllData=true)

public class RelatedController1Test {

static testMethod void testRelatedController1() {
// Select an actual proposal record from Proposal__c
Proposal__c p = [SELECT Id, Name FROM Proposal__c WHERE       Name=’Test Proposal Dekra’ LIMIT 1];
// Clone the selected proposal record and set some of the fields
Proposal__c testProposal = p.clone();

testProposal.Name = ‘Acme Test’;
testProposal.Scope_of_Work__c = ‘test’;
// Create the test proposal record
insert testProposal;

// Create the test project record and set the related Proposal__c field equal to the Id of the newly created test Proposal__c.Id.
Project__c prj = new Project__c();
prj.Name = ‘test’;
prj.Proposal__c = p.Id;

insert prj;
// Now run the test by instantiating the RelatedController1 class and calling the PopulateProject() method. This test gives 100% coverage.
Test.startTest();
ApexPages.Standardcontroller std = new ApexPages.Standardcontroller(prj);
RelatedController1 clsObj = new RelatedController1(std);
clsObj.PopulateProject();
Test.stopTest();
}
}

When the test has run successfully you are ready to create an outbound Change Set containing  two files, the RelatedController1 Apex class file and the Visualforce page, and deploy them into your Production org.

Salesforce Platform Workshop

Living in Atlanta gives me the opportunity to attend many top quality technology events entirely free of charge (except for an occasional parking fee). I recently attended one such event…a one day hands-on development class held at the Atlanta Salesforce offices, located on the 33rd floor of the One Atlanta Plaza building in Buckhead just across the street from the Lenox Marta Station…nice location!

buckhead
View of Buckhead skyline from Atlanta Salesforce Offices

The class, Salesforce Platform Workshop, was standing room only and they actually had to bring in extra chairs to accommodate additional unexpected attendees. A printed workbook was provided but you could also follow online at http://bit.ly/atlantadevworkshop.

Class entailed a series of hands-on exercises building a conference management application from scratch that included applying some of the latest Force.com technologies, Process Builder and Lightening Connect.  We even entered and deployed some Apex code for triggers to send email notifications whenever new records were entered. We ran out of time before the final module, deploying an app on Heroku and using the Salesforce REST APIs, but since we have the workbook I was able to work through this module afterwards on my own.

Two best tips I picked up were (1) you can’t make a standard object the detail in a Master-Detail relationship and (2) always put the relationship field on the object that needs to lookup, a concept I often get confused about.

The most valuable part of the day for me was working through an exercise using Lightening Connect to sync an external data source via a REST interface so that it looks like part of the Force.com application. This was something I wasn’t aware of prior to the workshop and something I can put to use immediately.

All in all a good day…much thanks to the local Atlanta Salesforce team for hosting the workshop!

 

 

 

Salesforce Elevate Workshop Atlanta Rocked!

On January 15th I was lucky to get to attend a sold out hands-on developers workshop, Salesforce Elevate, held in midtown Atlanta’s Proscnium Building.

The entire outline for the course is available at http://bit.ly/elevate-intro.

We started from scratch by signing up for a clean new Salesforce Developers account, then diving into declarative programming, Apex, SOQL, DML, Triggers, Visualforce Pages, and Controllers all before noon.

After lunch the class dove into the advanced portion of the workshop. The outline for which can be found here:  http://bit.ly/elevate-advanced.

Subjects covered in the afternoon were, Using javascript in Visualforce pages, Salesforce1 Platform APIs, Using Static Resources, Canvas Applications, Writing Tests, and Batching and Scheduling.

It was definitely a full day for a workshop that included something for everyone, with both beginner and experienced Salesforce developers able to gain a good amount of information from the materials and exercises and interactions with the instructors who both did an awesome job!

Cloudforce 2012 Rocked in Atlanta

 

Attended Cloudforce in Atlanta, held at the Georgia World Congress Center on Thursday, November 1st. I’ve attended all of the past Cloudforce events in Atlanta and I have to say this year was the best and the biggest! I have no idea how many attendees were there but it must have been thousands…well 2000 at least. The marketing extravaganza at Cloudforce is always amazing…but this year was taken to a new level…blowing off the doors with glitzy videos and music pounding out a message…of what I’m not sure…but the effect was awesome…I was pumped!

There were keynotes on different product lines, Cloudforce expo with a couple dozen 3rd party vendors on display ready to answer questions and demo products, numerous break out sessions, and the main keynote featuring Vivek Kundra, former chief information officer for the USA, now a senior VP at Salesforce.

At the Cloudforce main keynote I learned about new products and features like the ipad app, Chatterbox (file sharing), Desk.com, Work.com, and Chatter Communities. But the thing that always impresses me most at these Cloudforce events is the customer testimonies. We heard from GE, Toyota, E-Trade, Coca-cola, Virgin Airlines, and Commonwealth Bank (largest bank in Australia) just to name a few. Most memorable was the Toyota “social car”  which they termed the “iPhone of cars” and Coca-cola’s freestyle machines where you can create your own custom drink and then share it with friends.

Two  breakout sessions I enjoyed were “Social in Government” and the Salesforce Platform keynote. In the government session we heard from GSA’s region 4 IT exec on how the GSA used Force.com to consolidate 1700 legacy applications into 15 and then built 26 new applications in less than 6 months. All 17,000 GSA employees and contractors are on Force. We also saw examples of how Salesforce platforms are being used throughout the CDC, FDA, and New Jersey Transit Authority. In the Salesforce Platform keynote we heard from the Intercontinental Hotel Group and Home Depot where both companies built field inspection applications with Force.com. In viewing the demos I also picked up a cool new feature I didn’t know about called schema builder…not to mention two free books.

The most exciting thing I learned overall at Cloudforce was the new Salesforce Touch platform, which drives Salesforce mobile apps and allows enterprises to build their own mobile applications for Android and iOS platforms in either native or HTML5 hybrid modes. One of the free books provided to attendees of the Salesforce Platform keynote was the mobile development guide for the touch platform. I’m looking forward to giving this a try ASAP!

 

Force.com Dev 501 Class

The week of October 10th I was fortunate to have the opportunity to attend Force.com’s Dev 501 class in Atlanta. This class went beyond the declarative capabilities of Force.com covered in Dev 401 and expanded into APEX and Visualforce controllers.

Apex is an object oriented  programming language,  similar to Java and C#,  for building software as a service (SaaS) applications on top of Salesforce.com’s customer relationship management (CRM) functionality.  Apex gives developers access to Salesforce.com’s back-end database and metadata objects to create third-party SaaS applications. These 3rd party applications are offered for sale or free of charge in the Salesforce AppExchange marketplace, similar to the Apple and Android app stores.

Visualforce is a framework that includes a tag-based markup language,  similar to HTML or ASP.Net.

In the Visualforce markup language, each Visualforce tag corresponds to a user interface component, such as a section of a page or a field. The behavior of Visualforce components can be controlled by the same logic used in standard Salesforce pages, or developers can create  their own logic with controller classes written in Apex.

The Dev 501 class covers an amazing array of topics…just a few of which are APEX triggers, Force.com IDE Eclipse plugin, development sandboxes, SOQL queries, DML (data modeling language), deployment from sandbox to production organizations, consuming web services, and unit testing Apex classes.

Format of the class was lecture mixed with hands on exercises reinforced by formal questions answered out loud by attendees at the end of every lecture and exercise.  This was actually the most challenging formal training class I have attended since college…and also one of the best.

 

 

August Salesforce Meetup was the best one yet!

I’ve attended a few Salesforce User Group meetups in Atlanta over the past couple of years and being a big fan of Salesforce enjoyed each one. First unlike most other local technology meetup groups they are held in the morning not the evening. Second meetings are held at different venues around Atlanta…places like Home Depot, St Joseph Hospital, and Manhattan Associates. It’s interesting to get a glimpse inside all these different organizations.  Third they normally have a sponsor who provides breakfast and most important…coffee! Last but not least and the main reason I go to these meetings is the learning experience from 2-3 speakers on a wide variety of Salesforce and Force.com subjects. Talks are typically short 15-30 minutes each with demonstrations and time for questions. I always learn something new at each meetup but this August meeting was the best so far. The very first talk was by a pre-sales consultant (sorry can’t remember his name) from Informatica who walked us through a demonstration integrating two end points…Salesforce and an on-premise Oracle database. Coincidentally I’m starting a new project where I need to connect Salesforce to an on-premise Microsoft SQL Server and so needless to say I was transfixed by what I was seeing…the perfect solution to my current biggest problem! After the meeting upon returning to my office at Georgia Tech I immediately signed up for an account at Informatica, downloaded and installed the free lite version of their small footprint “agent”  onto my local Windows 2003 server where my SQL Server database is running. And by the end of that day I was syncing my Salesforce org with my local SQL Server…whoohoooo! Now that’s what I call getting value from a user group meetup!

Two 0ther presentations at the meetup covered exception reporting by James Martucci an instructor at Salesforce, and the Salesforce partner portal  by Venkat Polisetti, Senior Applications Developer at Fiserv Bank Intelligence Solutions. Both presentations contained useful information that I should be able to apply at work over the next few weeks.

Props to Venkat Polisetti who runs these meetings and always does a great job lining up speakers, coordinating with event sponsors,  and communicating the specifics out to group members.

 

 

 

Learning to build apps in the Cloud with Force.com

Just got home after a great week attending a Salesforce class, Building Applications Using Force.com and Visualforce. The class was held at MicroTek training center located at 230 Monroe street downtown Chicago. This is first of two main dev classes for Force.com covering mostly the declarative aspects of Force as well as Visualforce pages. By declarative I mean “point and click.” While Force.com contains a full blown object oriented programming language, APEX, and follows the MVC (model, view, controller) software architecture…this class didn’t cover programming…although we did get a good introduction to Visualforce pages.  Visualforce pages are a combination of html, javascript, and APEX tags that enable  the creation of custom pages (views) that utilize standard Force.com controllers. What we didn’t cover in this class was creating custom controllers with the APEX language.

For learning to develop custom controllers using APEX Salesforce offers another 5 day class,  Dev-501 – Apex and Visualforce Controllers…which hopefully I’ll get to experience sooner rather than later.

So now I’ve got a week of in depth training…a Salesforce account with 10 seats…a couple of big projects on the horizon at work where I can apply my newly learned Force.com skills…which makes me all set for an interesting Fall I think.

I stayed at the Hampton Magestic 22 West Monroe…a short walk from where my class was held at Microtek. (see photos below).  This was an outstanding place to stay…conveniently located in the middle of the Theater and Financial districts and only a couple of blocks away from Grant Park and the lake. Clean, reasonably priced…great breakfasts every morning too! I’m staying here every time I’m in Chicago from now on!

Every day after class I went for a run along the shore of Lake Michigan and the Chicago River (see pics below). Even though it’s August the temp each day was pleasant with a cool breeze blowing in from the lake…pure heaven coming from Hotlanta…especially this Summer one of the hottest on record.  And I wasn’t alone there were hundreds of other runners, walkers, and bikers on the same paths with me…very cool!

I tried to sample some traditional Chicago food…a slice of pizza and a hot dog…other than these two “samples” I went with fish and chips every evening. It wasn’t the healthiest week of my diet this year that’s for sure but I survived!

One observation about Chicago I have to mention…NO SMOKING inside any building…not a bar or pub or anywhere! And no smoking within 15 feet of any entrance either so you weren’t forced to hold your breath as you entered buildings. What a great idea! Who knows maybe Atlanta will get up to speed on eliminating this health risk one of these days too! But I doubt it.

Last but not least (well maybe so 🙂 I gained two Foursquare mayor ships in Chicago…Microtek and a small French restaurant along the Chicago river running path. It was a good week!

 

The "Bean" in Millenium Park was very cool!
The CTA blue line took me from O'Hare almost to my hotel door for only $2.25!!!

The Hampton Magestic was a great place to stay...highly recommend!

Street scene from the Microtek building at 230 Monroe Street
Fish and chips from Millers pub was absolutely yummy
The water fountains at millenium park were something different for sure!
Running path along the Chicago River
Cyrano's on the river along the running trail...I became mayor of this place! 🙂
Scene along the Chicago river running trail
Running path along Lake Michigan...cool breeze even in August.
Another scene along the Chicago River running path
Fantastic hot dog (Chicago Red Hot) at Halsted Street Deli
The "Bean" at millenium park
Everyone takes their pic in front of the Bean!

 

 

Atlanta CloudForce 2011

On May 19th CloudForce 2011 Atlanta was held at the downtown Hyatt. As always this event was outstanding with an informative keynote and interesting breakout sessions throughout the afternoon lasting until 5:30.  Registration began at noon and a nice lunch was provided in the exhibitor area up until 1pm when the keynote began. This year I had to come and go as I had meetings back at Georgia Tech I couldn’t miss. Good exercise as I walked the 1.5 miles back and forth to Tech Square several times this day. As you see in the photos I made sure I was there in the afternoon in time for the evening reception!

 

Keynote at Cloudforce Atlanta 2011
Registration area at the Atlanta downtown Hyatt
Salesforce Cloud projected onto the walls
Free beer and wine!
There were bars setup out doors too!
Last shot of the reception on my way out the door.
Out door patio at the Hyatt