Teach Me Salesforce

A community approach to learning salesforce.com

Archive for the ‘Intermediate’ Category

Unit Tests: Not Just for Dev – Idea 1

leave a comment »

Unit tests offer much more than just the means to get 75%+ code coverage, and they can be used to protect more than just Apex. Read the intro to this series in Idea 0.

Our first example is the simplest: protecting fields that you don’t want deleted. A use case for this is External Integrations that rely on Salesforce fields. If someone tries to delete the fields, you want to ensure that they are alerted to the impact. By including the fields Current Generators and SIC Code in the example Unit Test below, an attempt to delete the fields will throw an error referencing the unit test.

private class UnitTest1 {
    static testMethod void protectFields(){

    /*Create a new Lead, populating any Fields you need to protect
    * In this case, we want to ensure Current Generators and SIC Code cannot be deleted
    * or the field type changed by including them in this Apex Unit Test
    Lead l = new Lead(Company = 'Test Lead',
                      LastName = 'Lead Last Name',
                      CurrentGenerators__c = 'Generator X',
                      SICCode__c = '1234-ABC');
    insert l;

Let’s describe what’s happening here.

We start off with the all-important @isTest flag. This tells Salesforce that the Apex Class contains only test Methods. That means nothing you do in the Class will be saved to the server, and will not delete or change anything on the server. It also means you cannot use most records that exist on the server, so you have to create your own test records.

@isTest means that Salesforce will recognize it as a test Class, and when you Run All Tests, it will know to run this test too.

Next is the Class Name, UnitTest1 and its access modifier is set to “private”. Access modifiers are irrelevant for Unit Tests, private is the default.

The actual test Method here is protectFields(). Your test exists between the curly braces {}. Here you must create your test records and perform any actions you want tested. The critical item here is “testMethod” which ensures that Salesforce recognizes the method as performing tests. Without this, Salesforce will not report a test failure regardless of the outcome.

In this case we are creating a Lead. We are using standard Apex code to create a Lead, to populate fields on that Lead, and finally to use DML to insert the Lead. Required fields and Validation Rules will get enforced when you create the Lead, so be sure to include any fields affected by them.

Once this Unit Test is saved to the server, any attempt to delete the field or change its data type will be blocked with a reference to this Unit Test.

For this limited scenario, that’s all we need!


Written by Always Thinkin

August 3, 2014 at 3:53 pm

Posted in Apex, Code Sample, Intermediate

Tagged with ,

Unit Tests: Not Just for Dev – Idea 0

leave a comment »

This post is kicking off a series of posts about how Salesforce Admins & Developers can use Unit Tests for more than just testing Apex. The target audience is Admins who haven’t written Unit Tests. The ideas for Unit Tests here are intended to be easily copied and modified by anyone with System Admin access, a Sandbox or Developer Edition Org and a need to add a little more protection to their hard-won successes in building their org.

Unit Tests are designed to test Apex Triggers and Classes. They are required for deploying them to Production, but more important they are an essential tool to ensure that your logic, both Apex and declarative, does what it’s supposed to do, and nothing more or less.

But how else can they be useful?

Protection Integrations: Many Salesforce Orgs are now integrated with other applications and rely on the fields in Salesforce to, well, exist. And not to change or get locked down. Unit tests can be used to protect all the fields an integration uses against deletion, against changes to field type or restrictions by Field-level Security or Validation Rules.

Testing Declarative-only Apps: All those Clicks-not-Code components can add up to a complex series of Workflow Rules, Formula Fields and Validation Rules where you’ve got an application that is vulnerable to even slight changes. Unit tests can be used to ensure that a series of related Rules and Fields perform as expected, and that changes don’t disrupt the outcome.

And that application’s complexity can become difficult to test when there are hundreds of combinations of fields and their values. Throw in the ability to mass edit records in Views or Data Loader and you’ve got hours of manual tests to perform. Unit Test can be written to try all the combinations you want to throw at it, for hundreds of records.

The Ideas and Unit Tests in this series are all written using the sample data and metadata from the Developer Edition Orgs. Where necessary, I’ll add some new Workflow Rules, Validation Rules and Fields to come up with viable scenarios. If you don’t already have a Developer Edition org, you can get one (or one hundred) free Orgs at developer.force.com.

Because it’s so handy, we’ll use the Developer Console to write and run the Unit Tests, but you can also use the Force.com IDE for Eclipse, MavensMate or even the declarative interface.

You won’t need to know much Apex. I’ll attempt to explain the parts that are not intuitive, or just advise you to do-as-I-do if the explanation won’t help (or I don’t know either).

So put your pencils down, Testing time is up: Idea 1

Written by Always Thinkin

August 3, 2014 at 3:28 pm

Posted in Apex, Intermediate, Validation, Workflow

Tagged with ,

Apex – Sorting a map

leave a comment »

So this is going to be one of the more apex heavy posts. This is a challenge I think many developers
have come across, and while what I propose is by no means the most elegant thing ever, it does do the
job until hopefully salesforce implements a native map sorting method. So here is the basic approach

1) populate map with information
2) create another map with the keys as the values you want to sort by, and the value as the key
for the other map.
3) create a list whos values are the keyset of the map created in step 2
4) sort the list
5) iterate over the list which now has your values in order, get the value from map 2 using the
current loop iterator as the key.

Sounds pretty complicated eh? It’s not SO bad once you kinda get the hang of it, but there is one
gotcha that kind of sucks, but we’ll cover that in a minute.

Here is a sample using a simple object called contestEntry. We’ll create a bunch of them with
random ordering, and then sort them and loop over the sorted result. You should be able to run this
in any org so you can see the principals in action.

        public class contestEntry
            public decimal rank{get;set;}
            public string name{get;set;}

        map<string,contestEntry> entries = new map<string,contestEntry>();

        contestEntry entry1 = new contestEntry();
        entry1.rank = 5;
        entry1.name = 'Frank';

        contestEntry entry2 = new contestEntry();
        entry2.rank = 3;
        entry2.name = 'Bob';

        contestEntry entry3 = new contestEntry();
        entry3.rank = 1;
        entry3.name = 'Jones';

        contestEntry entry4 = new contestEntry();
        entry4.rank = 4;
        entry4.name = 'Sandy';

        contestEntry entry5 = new contestEntry();
        entry5.rank = 2;
        entry5.name = 'Felix';

        //oh no, these entries are all out of order.
        system.debug(entries) ;

        //lets get sorting these guys. First we'll need a map to store the rank, and the contestEntry that rank is
        //associated with
        map<decimal,string> rankToNameMap = new map<decimal,string>();
        for(contestEntry entry : entries.values())
        //now lets put those ranks in a list
        list<decimal> ranksList = new list<decimal>();

        //now sort them

        //ok, so now we have the ranks in order, we need to figure out who had that rank
        for(decimal rank : ranksList)
            String thisEntryName = rankToNameMap.get(rank);
            contestEntry thisEntry = entries.get(thisEntryName);

Walking through it first we just make a sample object to use here. Normally this would be whatever you are actually trying to sort, but for the sake of easyness I just created an object called contestEntry. It just holds a name and a rank.

So then I make a map of those things, keyed by the persona name, and containing the contestEntry object. You might in real life have a map of sObjects keyed by their Id and containing the sObject itself. So then I make a bunch of those and add them to the map in random order so my sorting actually has some work to do 😛

The next thing is creating a map with the key of the value I want to sort this list by. The value is key of the first map. So in real life this might be a dollar amount on an opportunity and then the opportunity Id if the original map was a list of opportunities keyed by their Id.

We loop over all the objects in the original map, and add them to our temporary sorting map, again keyed by value to sort by, and value with key from original map.

Then we create a list of the type of the key of the temporary sorting map. Your key was a decimal? Then your list is of decimals as well, etc. Then add all the keys from the sorting map to the list you just made.

Sort the list.

Iterate over the sorted list, each entry in this list will be a key you can use to get the entry from the sorting map, which will contain the key to the original map. You now have a reference to your original map value by whatever value you sorted on.

There is however one gotcha with this approach. If you have duplicates in the value you are going to sort by, you are going to end up with collisions in your sorting map, which will end up with values overwriting each other and ultimately values missing in your final iteration. This happens because say in my example I have two people with rank 1. First person comes through, their rank is 1, and their name is Sandy. So the sorting map has 1=sandy. Then another person comes through, they also have rank 1 and their name is jones. Now the map has 1=jones. Sandy just fell out of the list. How do you deal with this? The best hack-ish fix I could come up with is to see if the key you are attempting to write to already exists, if so, then write to a slightly higher value key. Basically replace

       for(contestEntry entry : entries.values())


for(contestEntry entry : entries.values())
                decimal rank = entry.rank;
                    system.debug('------ INCRIMENTING Rank TOTAL FOR ' + entry.name);
                    rank += 0.001;


This won’t affect the value displayed when you retrieve and display the object, it just changes the sort order. I haven’t tested this throughly though so don’t rely on it extensively.

Anyway, there you have it Apex fans. A method to reliable (if not quickly or efficiently) sort Apex maps by just about anything. Once you understand the concepts it’s fairly easy to expand to sort to your hearts desire.
Originally posted by Kenji776 @ http://iwritecrappycode.wordpress.com/2011/09/28/apex-sorting-a-map/

Written by kenji776

September 28, 2011 at 5:07 pm

Mastering the Force.com IDE: Searching metadata

with 17 comments

The Force.com IDE is a developer application that is great utility for Salesforce.com administrators even if they never have to write or troubleshoot Apex or Visualforce. The most useful capability for any admin is the Search feature which allows you to find all the places a field is used: workflow, reports, templates, formulas, etc.

Let’s consider this scenario: you’ve been hired to update a company’s Salesforce org and you discover a duplicate field on Accounts. You run reports and find out both fields are populated with data. Before you can decide which one to keep and which to delete, you need to know all the locations in which each field is used: reports, views, workflow, templates, etc. You can find all those configurations in minutes with your Salesforce org’s metadata in a project in the Force.com IDE.

I’ll assume you’ve already installed Eclipse and the Force.com IDE. If you haven’t, developer.force.com has a great page to help you; see you back here soon!

The first step is to create a Force.com project that contains all your metadata. Do this during the set up by selecting all the Metadata components.

New Force.com Project Wizard: Choose Initial Project Contents

New Force.com Project Wizard: Choose Metadata Components

If you have a very large amount of metadata and Eclipse throws a Java Out of Memory error, you can either apply this solution or choose fewer metadata components. You should at least include the following to ensure you are searching the common components that reference fields.

Component file extension
Apex Classes
Visualforce Components
Email Templates
Page Layout
Custom Objects
Standard Objects
Object Translations
Visualforce Pages
Reports(includes reports built from Custom Report Types)
Apex Triggers

Once you have created your project, you’re ready to start your search!

  1. Click on your Project to highlight it
  2. Click on the Search menu in the menu bar and select Search… to open the Search dialog box
  3. Enter the API Name of the field you’re seeking in Containing Text
  4. Copy the following file extension names into the field called File Name Patterns:
    *.cls, *.component, *.email, *.layout, *.object, *.page, *.profile, *.report, *.scontrols, *.trigger, *.workflow
  5. Set the Scope option to “Selected Resource” to ensure that only one Project is being searched.
  6. Click Search
  7. The Search Results pane will open when your search is completed with a list of all locations where the field occurs.

The following video demonstrates these steps in the Force.com IDE for Windows (Mac version is similar)

The search results will show you a tree with all the results in each metadata component. Click on any result will open the metadata file and show you exactly where your field occurs. You’ll be viewing XML, but don’t worry if you’ve never looked at XML before, there’s nothing tricky here. In fact, the tags you see are very friendly. They’ll be “nested” which means indented like a outline so that you can tell which tags are subordinate to which other tags. With a little investigative analysis, you’ll be able to discern the exactly how a field is being used in the metadata.

For example, in this screenshot you can see the Search results pane showing the components in which the field was found. The Reports components are open and the report called “Server Alerts” has two matches. By clicking on the matches, the Server_Alerts.report XML file is opened and the matches are highlighted. In the XML you can see all the configurations for this particular report. The <columns> tags show which columns are displayed in the report’s output, so we can see that our “App Server” field is one of the output columns.  We also see the field nested in the <filter> tags and can translate the XML tags to tell us that the field is being used in a filter with the operator “notEqual” and no value which means we are looking for records where App Server is not populated with any data. You can compare it to the actual report in the UI which is depicted in the second image below.

Screenshot shows the Search Results panel for a metadata search and the XML for the field as it occurs in a custom report.
Here’s how this report looks in the declarative UI for comparison. Note how the fields selected in the report show up as <column> tags and the filter is divided up into <filter>, <criteriaItems>, <column> and <operator> tags.
Using the Force.com IDE for metadata searches is one of my favorite techniques for thorough database maintenance. Searching with the IDE is just a start. From the results, you can even update many components with a simple Find and Replace to replace the retired field with a new field…but we’ll save that for the next lesson in Mastering the Force.com IDE!

Update 2013-11-06: Since Summer ’13 you can also use the Developer Console to search for fields across all Apex Classes and Triggers. Admittedly not as thorough a search of metadata as you can do in the IDE but it’s a good start – let’s hope we get the rest of the metadata world in there in a future release!

Written by Always Thinkin

September 25, 2011 at 2:48 pm

Visualforce Code Generator

with 9 comments

This is a cross post from my Blog Post.

We know how much important role visualforce plays in our application. There are many instance where we need to create a visualforce page and apex class. Salesforce provides powerful tools like workflows, approvals, validation etc. from which we can implement our business functionalities with just button clicks.

Now I was having a requirement where I need to create many visualforce pages, some are custom and some are cloning native page with native layouts with some small changes. This just clicked me to create a tool from which we can create a visualforce page code with just clicking buttons. Yes!! Visualforce page code with button click.

This saved a lot of time, as I do not need to write any thing to create a heavy visualforce page and amazingly it is done just using button clicks.

Install the package : https://login.salesforce.com/packaging/installPackage.apexp?p0=04t90000000Pqos

Just append “/apex/vfgenerator__codegenerator” in URL.

Now let me jump into the explanation what exactly I have done. A simple UI will be displayed, where user can select the desired type of page, object name, record type, email field.

Object Name : Valid object API name (include namespace if any)

Record Type : Record type Id of object selected in Object Name
Type of Page :

  1. Edit : Code will be generated for the edit page of the object (according to “record type” layout if selected any).
  2. Detail : Code will be generated for the detail page of the object (according to “record type” layout if selected any)
  3. Custom Detail : Code will be generated for detail page according to the fields selected from UI
  4. Custom Edit : Code will be generated for edit page according to the fields selected from UI

In the above screen I have selected “Edit” as the type of page and “Account” in object, also provided my email. When I click “Generate Code” it displays like this :

Just copy the code and paste it in new visualforce page. Why I have given my email id because when you paste the code in visualforce page it will loose all the formatting and will display in one single line, but code sent on email will come with formatting. So we can copy the generated code from email also. Now when you hit the newly created visualforce page it will display all fields in edit mode which are displayed on native edit page. Isn’t that good?

Now lets try creating some custom visualforce page. Select “Custom Edit” in “Type of Page” and “Account” in “Object Name”. It will display a section “Select Fields”. Click on “Display Fields”, it will display all fields which are up datable by present user.

Select some fields and click on  “Generate Code”. Again copy paste the code in your visualforce page, it will display selected fields in edit mode.

Now heavy visualforce pages are created with just button clicks.

Package provided is managed because the tool is under testing and I would like to have feedback from you all. Once it is free from all bugs I will provide the code.

Declaration: You may find similar post related to “Visualforce Code Generator”. The end result may be similar but there is a considerable difference in the approaches being followed here. So I, hereby declare that my project is entirely my own creation and has not been copied from any other person/organization’s words or idea. Please feel free to drop me an email at “arora.salesforce@gmail.com” if there is any disagreement.


Written by Ankit Arora (forceguru)

June 15, 2011 at 2:32 pm

Writing Good Test Methods

with 7 comments

Yesterday Rebecca (@sfdc_nerd) posted about her first trigger.   She did a great job and even got 100% coverage from her test class. Rebecca had actually posted this on her own blog: A force behind the force a few days earlier and I noted that she needed to do just one more thing in her test class to make it a real test. The one thing she didn’t do was check that the trigger actually created the record it was supposed to create and we sorted that out with a phone call and an email. Afterwards I started thinking that it would be good to explain what a test method really needs to be “complete” and figured I would post it here.  I have come up with a slightly contrived example below to illustrate some extra points.

I often see test classes written which achieve the necessary code coverage but aren’t exactly “tests”. Salesforce.com requires at least 75% code coverage to deploy code to a production environment. Some developers then see 75% as the goal and are happy once they cross that threshhold when they should really be shooting for 100%. Now, if you have spent any time doing development in Salesforce, you know that 100% coverage is sometimes impossible, but we should at least aim for 100%.

With that in mind, I wanted to dissect a simple test class to explain (in my opinion at least, please feel free to chime in) what you should be aiming to achieve when writing a test class.

Consider the following trigger which creates a task to call the lead when the lead is created. The due date of the lead should be 7 days from today unless a lead for a member of the very important ‘Elephantman’ family calls in. Then we will make the task due tomorrow (sorry about the formatting, wordpress doesn’t like me today).

trigger newLeadTask on Lead (after Insert) {

 List<Task> taskList = new List<Task>();
 for(Lead l : trigger.new){
 Task t = new Task(Subject = 'Contact Lead',
 WhoId = l.id,
 Status = 'Not Started', 
 OwnerId = l.OwnerId);

 if(l.LastName <> 'Elephantman'){
 t.ActivityDate = Date.today()+7;
 t.ActivityDate = Date.today()+1;

 insert taskList; 

In order to test this, we must write a class which will insert a lead. Inserting the lead will cause the trigger to fire and the code will be executed.

private class testLead{
    private static testmethod void testLeadActivity(){
        Lead l = new Lead(LastName = 'Randomname', Company = 'ABC, Inc.');
        insert l;

Running this test we see that we get 87% coverage of our trigger. Awesome, we are ready to deploy to production because we are above 75%. Well, yes, but we are aiming for 100% here if we can get it.

We need to think of the test method as sort of a stand in for a human tester. If you asked your colleague to test this trigger, you would expect them to create a lead. Once the lead was created you would then expect them to actually check that the task was created. Well, let’s do that. After we insert the lead, let’s query for the newly created task; we should expect that 1 (and only 1) exists and that it has a date 7 days from today:

private class testLead{
    private static testmethod void testLeadActivity(){
        Lead l = new Lead(LastName = 'Randomname', Company = 'ABC, Inc.');
        insert l;

        List<Task> taskList = [SELECT id, ActivityDate from Task WHERE whoId = :l.id];

The first System.assertEquals statement equates to our colleague checking that the task was actually created, the second statment checks that the date is correct. Great, so now we have a valid test but we still haven’t tested everything. The logic of the trigger says that if a lead is created for a member of the ‘Elephantman’ family, then the task due date is the next day. We expect our colleague to test both use cases, so we will do the same.

@isTest //indicates this is a test so that the code below doesn't count against our quota
private class testLead{
 private static testmethod void testLeadActivity(){
 //insert a random (non Elephantman lead)
 Lead l = new Lead(LastName = 'Randomname', Company = 'ABC, Inc.');
 insert l;

 List<Task> taskList = [SELECT id, ActivityDate from Task WHERE whoId = :l.id];

 //insert an Elephantman lead
 Lead eMan = new Lead(LastName = 'Elephantman', Company = 'ABC, Inc.');
 insert eMan;

 List<Task> eManTaskList = [SELECT id, ActivityDate from Task WHERE whoId = :eMan.id];

When I run this test I get 100% coverage and I know that I have fully tested all use cases for this trigger. I can now deploy this to production.

Beyond being good practice, there is a very good reason to write your test classes as completely as possible. On a recent salesforce.com Webinar, I heard it mentioned that Salesforce actually runs ALL, yes ALL, test methods across all orgs before upgrading them to a new release. By writing your test methods properly, you are helping ensure nothing breaks when Salesforce updates to a new version.

Written by knthornt

May 17, 2011 at 9:30 am

Posted in Apex, Intermediate, Trigger

Trigger to create a new record

with 13 comments

Ask me a year ago, and I never thought I’d be writing triggers, but yet, here I am. I gained a bit of confidence after taking the Salesforce DEV 531 class, and that confidence then flourished with the support of this community. This blog just goes to show how many people out there are willing to help, and I definitely want to return the favor whenever possible. So here goes – the anatomy of my first trigger.

What I was looking to do was to create a new support request record (a custom object) when a new Event record of a specific type was created. Pretty straight-forward, but definitely not doable without a trigger. The final result was this:

trigger createPDtask on Event (after insert) {     
List<Support_Request__c> sr = new List<Support_Request__c>();
    for (Event newEvent: Trigger.New)
         if (newEvent.Type__c == '1. Meeting - Initial'){
                 sr.add (new Support_Request__c(
                     Name = 'New PD',
                     Task_Type__c = 'PD',
                     SFDC_Record_ID__c = newEvent.Id,
                     Rep__c = newEvent.OwnerId,
                     Event_Date__c = newEvent.ActivityDate));   
   insert sr;

Now for the breakdown of what I was trying to do with each step. First, I define what I want the trigger to do & when to do it.

trigger createPDtask on Event (after insert) {

The second line compiles all new records I am going to insert into a list (& therefore takes care of bulkifying my trigger).

List<Support_Request__c> sr = new List<Support_Request__c>();

Then I need to define the criteria around the event record that would cause this trigger to create a new support request.

for (Event newEvent: Trigger.New)
         if (newEvent.Type__c == '1. Meeting - Initial'){

Next, I set the details that get inserted into the new Support Request record. You can see that some are static, while a few are dynamically pulled from the event record.

sr.add (new Support_Request__c(
                     Name = 'New PD',
                     Task_Type__c = 'PD',
                     SFDC_Record_ID__c = newEvent.Id,
                     Rep__c = newEvent.OwnerId,
                     Event_Date__c = newEvent.ActivityDate));

Finally, the list gets inserted.

   insert sr;

As far as triggers goes, it’s pretty simple, but it was a great learning process for me to build on my own. From here, the next step is to write some test coverage, and while I thought I had it in the bag, I’m going to let Kyle share the lesson he gave me in a subsequent post.

Written by Becka

May 16, 2011 at 10:10 am

Posted in Apex, Beginner, Intermediate, Trigger

Tagged with