Template for Global Configuration Variables in Apex

Summary: This article discusses a pattern or template for enabling and customizing features in an application developed upon the Force.com platform.

Force.com and “configurability”: new expecations for developers

A great thing about developing on the Force.com platform is how configurable the product is out of the box. Need a new field on a screen? Easy, find the right page layout and modify it. Want a field to be required? Go find the field and make it required. It’s crazy easy. So easy in fact, that more and more folks can contribute to the solution of a system. Even folks without an IT background that 5-10 years ago would never make these types of configuration changes are doing it. Can you imagine Joe the BA adding an Oracle constraint to make a field required? Of course not.

The downside to this amazing “configurability” of the Force.com platform however, is it creates a disconnect between developers who are not used to including this level of configurability, and salesforce users who have grown to love this type of configuration and now expect it in anything associated with salesforce. Below I discuss a “global configuration variable” pattern that makes adding configurability to your solution simple, clean and reliable.

What’s a global configuration variable?

A global variable (as opposed to a global configuration variable) is a variable which is accessible from any scope. It’s widely accepted that using global variables is a bad practice because those variables can easily be modified from anywhere within your codebase and as a result, using them becomes chaotic and difficult to debug. While similar in that its accessible from any scope, a global configuration variable should also be:

  1. read only (because it would be a bad practice if it weren’t)
  2. type cast (client code shouldn’t be burdened with type-casting a string to an integer)
  3. cached (each variable shouldn’t be loaded each time it’s accessed)
  4. sanity checked upon load (for example, a timeout shouldn’t be negative so default to 0)
  5. easily changeable in production (Joe the BA should be able to do it)

Usage

Best explained in a diagram:

What components are included?

  • GlobalConfigurationVariable__c.object: Defines the data store for the global configuration variables (I think I just sounded like George W Bush saying “the google”). If you’re unfamiliar with custom settings, essentially they are specialized custom objects whose records are cached in the Force.com application tier and accessing those records doesn’t burn any governor limits.
  • GlobalConfigurationVariables.cls: The main class which you’ll need to modify with your configuration variables. The example template is show below.
  • GlobalConfigurationVariablesTest.cls: Test class which you’ll need to modify as well.
  • GlobalConfigurationVariableTestUtils.cls: No need to modify. Unit test helper that makes achieving 100% code coverage much easier.
  • GlobalConfigurationVariableTestUtilsTest.cls: No need to modify. Unit test helper’s test class (yeah, I know the name is confusing but you shouldn’t need to touch this class or the unit test helper class).

GlobalConfigurationVariables.cls

/**
 * Please consider this class a template.  You will need to customize
 * this class according to the global variables you might require in
 * your application.  Also, you might consider creating multiple
 * classes similar to this broken down by global configuration variables that make
 * sense to be packaged together.
 *
 * First (1), define your global configuration variables as member variables of this class.
 * For example, if you're defining a twitter username as a global variable, then
 * the variable might be:
 *
 * public String twitterUsername {get; private set;}
 *
 * Next (2), define the key for your global variable.  This is the value which
 * must be entered as the name of the "Global Variable" custom settings record
 * defined at:
 *
 * Setup | App Setup | Develop | Custom Settings | Global Variable | Manage
 * (NOTE: if you haven't deployed that Custom Settings object yet, then obviously
 * the above won't be available.)
 *
 * The key can be the same value as member variable but that isn't required.
 * Using same example as above, the variable key might be:
 *
 * public static final String KEY_TWITTER_USERNAME = 'twitter.username';
 *
 * Third (3), define how the variable will be loaded.  Included are two
 * methods which read Strings and Integers.  If you have a different data type,
 * definie a different "retrieve" method.
 *
 * And last (4), consider putting in some sanity checking.  For example, if
 * you have a timeout variable defined as integer, perhaps it's a good idea
 * to make sure it's > 0 but less than 60000 milliseconds.
 *
 * Once your configuration variables are defined, you should access the configuration variables in your
 * code via the following:
 *
 * GlobalConfigurationVariables.getInstance().twitterUsername
 *
 * And I suggest you always call getInstance and you never store a reference of
 * the GlobalConfigurationVariables object.  That way, you can be assured that all transactions
 * will get the latest copy of the configuration variables AND only do it once.
 *
 * @author Richard Vanhook
 */
global class GlobalConfigurationVariables {

    //==================================================
    // (1) Define your configuration variables
    //==================================================
    global String exampleString {get; private set;}
    global Integer exampleInteger {get; private set;}

    //==================================================
    // (2) Define variable keys
    //==================================================
    global static final String KEY_STRING_EXAMPLE = 'ExampleString';
    global static final String KEY_INTEGER_EXAMPLE = 'ExampleInteger';

    private GlobalConfigurationVariables(){
        final Map<String,GlobalConfigurationVariable__c> all = GlobalConfigurationVariable__c.getAll();
        //==================================================
        // (3) Load configuration variables
        //==================================================
        exampleString = retrieveString(KEY_STRING_EXAMPLE, all);
        exampleInteger = retrieveInteger(KEY_INTEGER_EXAMPLE, all);

        //==================================================
        // (4) Do some sanity checking
        //==================================================
        if(exampleInteger == null || exampleInteger < 0 || exampleInteger > 60000){
            exampleInteger = 1000;
        }
    }

    //==================================================
    // HELPER METHODS
    //==================================================
    global static GlobalConfigurationVariables instance;

    global static GlobalConfigurationVariables getInstance(){
        if(instance == null){
            instance = new GlobalConfigurationVariables();
        }
        return instance;
    }

    private static Integer retrieveInteger(String key, Map<String,GlobalConfigurationVariable__c> all){
        Integer returnValue = null;
        if(all != null && !isBlank(key) && all.get(key) != null){
            try{
                if(all.get(key).value__c != null){
                    returnValue = Integer.valueOf(all.get(key).value__c);
                }
            }catch(System.TypeException e){}
        }
        return returnValue;
    }

    private static String retrieveString(String key, Map<String,GlobalConfigurationVariable__c> all){
        String returnValue = null;
        if(all != null && !isBlank(key) && all.get(key) != null){
            returnValue = all.get(key).value__c;
        }
        return returnValue;
    }

    private static boolean isBlank(String str) {
        return str == null || str.trim() == null || str.trim().length() == 0;
    }

}

Component install instructions:

  1. Unzip GlobalConfigurationVariables.zip to a local folder
  2. Open Eclipse and set up a Force.com project (steps for doing this are outside the scope of this article)
  3. Include object metadata components in your project (via right-click project -> Force.com -> Add/Remove Metadata Components)
  4. Drag and drop file GlobalConfigurationVariable__c.object into your objects folder
  5. Drag and drop class files into your classes folder

apex-lang 1.12 released

Biggest modification is the addition of SoqlBuilder classes.

SOQL Builder

It’s been my observation that one of the most error prone pieces of code any force.com developer will write is the code which builds a SOQL query. Think about it. How many times have you forgotten a comma, misplaced an AND, mis-formatted a date string, or worst of all, forgotten to escape user input?

These types of mistakes are silly for several reasons. First, they happen to everyone, second, they seem to happen over and over again – mainly during development but even still, that’s wasted time, and wasted time is wasted money. And the worst part is apex is a good enough language that the rules governing SOQL syntax should be apparent via a clear API. Something where many mistakes could be caught at compile-time – and just in case an error did occur at run-time, something that pinpoints the error better than “hey, your SOQL is invalid”.

My response is a concept called the “SOQL Builder”: a set of classes contained in the apex-lang library whose main class is appropriately called SoqlBuilder. My hope is this set of classes will alleviate force.com developers of having to remember the mundane details of SOQL syntax and provide them a developer friendly tool for creating SOQL. This article is quick introduction to SoqlBuilder followed by a full reference. I hope you find SoqlBuilder useful and if you have any suggestions for improvement, please don’t hesitate to let me know!

Basic Example

Let me start by showing a quick example. Given this SOQL query:

SELECT name FROM account WHERE employees < 10

Here is the corresponding code to create the query string via a SoqlBuilder:

new al.SoqlBuilder()
 .selectx('name')
 .fromx('account')
 .wherex(new al.FieldCondition('employees').lessThan(10))
 .toSoql();


NOTE: the above code sample assumes you’ve installed the managed package version of apex-lang. If you’ve directly included the apex-lang code in your org, then remove all al. namespace prefix references.

Right off the bat, you probably noticed the x’s at the end of some of the methods. Unfortunately, “select”, “from”, and “where” are all reserved words in apex and cannot be used as method identifiers. In order to get around this, I chose to append an x to the end of the method name (this convention is followed throughout other classes as well). Wish I didn’t need to append the x, but it is what it is. Another thing you might have noticed is the methods are “chained”. That helps make this code less verbose and feel more like a SOQL statement.

Benefits

Here’s a list of benefits to building SOQL queries using SoqlBuilder:

1. Reduces the risk of a silly SOQL grammar error
2. More readable / less verbose code
3. Automatic literal conversion
4. String escaping by default
5. Easy wild-carding

The first benefit is the reduced risk of misplacing an element. That’s the “silly” class of mistakes I mentioned earlier and whether it’s a parenthesis here or a comma there, it’s surprisingly easy to do. All String concatenation with SoqlBuilder takes place inside the super intelligent toSoql() method.

While it might not be true for simple cases (like the example above), using a SoqlBuilder will make your code less verbose and as a result, more readable. The construction of most real-world soql queries is an ugly, un-readable mess of String concatenation. Perhaps you’ve written or seen code like the following:

final Datetime aDatetime = DateTime.newInstance(2010,1,1,1,1,1);
final String aName = 'O\'Neal';
final List<String> aList = new List<String>{'Apparel','Auto'};
String soql = 'SELECT id,name,ispartner,industry';
soql += ' FROM account';
soql += ' WHERE CreatedDate < ';
soql += aDatetime.format('yyyy-MM-dd') + 'T' + aDatetime.format('hh:mm:ss') + 'Z';
soql += ' AND Name like \'%';
soql += String.escapeSingleQuotes(aName);
soql += '%\' AND industry INCLUDES (';
Boolean isFirst = true;
for(String anItem : aList){
 if(isFirst){
 isFirst = false;
 } else {
 soql += ',';
 }
 soql += '\'';
 soql += anItem;
 soql += '\'';
}
soql += ')';
System.debug(soql);

There’s no other way to put it: dude, that’s ugly code!

Here’s how the same query can be constructed using SoqlBuilder:

final Datetime aDatetime = DateTime.newInstance(2010,1,1,1,1,1);
final String aName = 'acme';
final List<String> aList = new List<String>{'Apparel','Auto'};
String soql = new al.SoqlBuilder()
  .selectx(new Set<Object>{'id','name','ispartner','industry'})
  .fromx('account')
  .wherex(new al.AndCondition()
    .add(new al.FieldCondition('CreatedDate').lessThan(aDatetime))
    .add(new al.FieldCondition('Name').likex(aName))
    .add(new al.SetCondition('industry').includes(aList))
  )
  .toSoql(new al.SoqlOptions().wildcardStringsInLikeOperators());
System.debug(soql);

The third benefit is automatic conversion of literals. From the example above (the SoqlBuilder portion), notice how the aDatetime variable is simply passed to the lessThan() method? The FieldCondition handles converting the date time to the appropriate format. Just in case you’re curious where that code is, see the toLiteral() method in the SoqlUtils class.

Another benefit which can be seen in the previous example is automatic escaping of single quotes. Notice that the aName variable is simply passed to the likex() method. When toSoql() is executed, all single quotes in all Strings will be automatically escaped! Imagine how much the AppExchange Security Review Team will like that!

Also, the previous example also shows how easily all Strings in LIKE operators can be wild-carded. By default, the “wildcardStringsInLikeOperators” property is set to FALSE. However, if you call the wildcardStringsInLikeOperators() method on a new SoqlOptions object, then it will do just that: all strings will be wild-carded on both sides.

Reference

For all examples below, the new al.SoqlBuilder() and .toSoql() portions are omitted. If you’d like to run one of the examples – using anonymous execute for example – then use the following snippet:

System.debug('\n\n'
+ new al.SoqlBuilder()
//insert example from below here
.toSoql()
+ '\n\n');



SELECT



Selecting Fields

.selectx('ID')
.selectx('Name')
.fromx('Account')
//-> SELECT Name,ID FROM Account
.selectx(new Set<String>{'ID','Name'})
 .fromx('Account')
 //-> SELECT Name,ID FROM Account
.selectx(new List<String>{'ID','Name'})
.fromx('Account')
//-> SELECT Name,ID FROM Account
.fromx('Account')
//-> SELECT ID FROM Account

count()

.selectCount()
.fromx('Account')
//-> SELECT count() FROM Account

toLabel

.selectx(new Field('Rating').toLabelx())
.fromx('Account')
//-> SELECT toLabel(Rating) FROM Account

Relationship Queries

.selectx('id')
.selectx(
  new al.SoqlBuilder()
  .selectx('id')
  .fromx('OpportunityLineItems'))
.fromx('Opportunity')
//-> SELECT id,(SELECT id FROM OpportunityLineItems) FROM Opportunity



FROM



.fromx('account')
//-> SELECT id FROM account
.fromx('Contact c, c.Account a')
//-> SELECT id FROM Contact c, c.Account a



WHERE



Field Condition

/*
You can create a field condition using any of the following formats:
new al.FieldCondition().field(fieldName).operator(value)
new al.FieldCondition(fieldName).operator(value)
new al.FieldCondition(fieldName,Operator,value)
*/
//the following four examples are equivalent:
.fromx('account').wherex(new al.FieldCondition().field('name').equals('acme'))
.fromx('account').wherex(new al.FieldCondition('name').equals('acme'))
.fromx('account').wherex(new al.FieldCondition('name',al.Operator.EQUALS,'acme'))
.fromx('account').wherex(new al.FieldCondition('name','acme'))  //special case only valid for equals
//-> SELECT id FROM account WHERE name = 'acme'

Field Operators (using Operator as constructor argument)

/*
+--------------------------+----------+
| enum value               | operator |
+--------------------------+----------+
| EQUALS                   | =        |
| NOT_EQUALS               | !=       |
| LESS_THAN                | <        |
| LESS_THAN_OR_EQUAL_TO    | <=       |
| GREATER_THAN             | >        |
| GREATER_THAN_OR_EQUAL_TO | >=       |
| LIKEX                    | like     |
+--------------------------+----------+
*/
.fromx('account').wherex(new al.FieldCondition('employees',al.Operator.EQUALS,1))
//-> SELECT id FROM account WHERE employees = 1
.fromx('account').wherex(new al.FieldCondition('employees',al.Operator.NOT_EQUALS,1))
//-> SELECT id FROM account WHERE employees != 1
.fromx('account').wherex(new al.FieldCondition('employees',al.Operator.LESS_THAN,1))
//-> SELECT id FROM account WHERE employees < 1
.fromx('account').wherex(new al.FieldCondition('employees',al.Operator.LESS_THAN_OR_EQUAL_TO,1))
//-> SELECT id FROM account WHERE employees <= 1
.fromx('account').wherex(new al.FieldCondition('employees',al.Operator.GREATER_THAN,1))
//-> SELECT id FROM account WHERE employees > 1
.fromx('account').wherex(new al.FieldCondition('employees',al.Operator.GREATER_THAN_OR_EQUAL_TO,1))
//-> SELECT id FROM account WHERE employees >= 1
.fromx('account').wherex(new al.FieldCondition('name',al.Operator.LIKEX,'acme'))
//-> SELECT id FROM account WHERE name like 'acme'

Field Operators (operator as method identifier)

/*
+----------------------+----------+
| method identifier    | operator |
+----------------------+----------+
| equals               | =        |
| notEquals            | !=       |
| lessThan             | <        |
| lessThanOrEqualTo    | <=       |
| greaterThan          | >        |
| greaterThanOrEqualTo | >=       |
| likex                | like     |
+----------------------+----------+
*/
.fromx('account').wherex(new al.FieldCondition('employees').equals(1))
//-> SELECT id FROM account WHERE employees = 1
.fromx('account').wherex(new al.FieldCondition('employees').notEquals(1))
//-> SELECT id FROM account WHERE employees != 1
.fromx('account').wherex(new al.FieldCondition('employees').lessThan(1))
//-> SELECT id FROM account WHERE employees < 1
.fromx('account').wherex(new al.FieldCondition('employees').lessThanOrEqualTo(1))
//-> SELECT id FROM account WHERE employees <= 1
.fromx('account').wherex(new al.FieldCondition('employees'.greaterThan(1))
//-> SELECT id FROM account WHERE employees > 1
.fromx('account').wherex(new al.FieldCondition('employees').greaterThanOrEqualTo(1))
//-> SELECT id FROM account WHERE employees >= 1
.fromx('account').wherex(new al.FieldCondition('name').likex('acme'))
//-> SELECT id FROM account WHERE name like 'acme'

Set Conditions

/*
You can create a set condition using any of the following formats:
new al.SetCondition().field(fieldName).operator(values)
new al.SetCondition(fieldName).operator(values)
new al.SetCondition(fieldName,Operator,values)
*/
//the following three examples are equivalent:
.fromx('account').wherex(new al.SetCondition().field('x').includes(new List<Object>{1,2}))
.fromx('account').wherex(new al.SetCondition('x').includes(new List<Object>{1,2}))
.fromx('account').wherex(new al.SetCondition('x',al.Operator.INCLUDES,new List<Object>{1,2}))
//-> SELECT id FROM account WHERE x INCLUDES (1,2)

Set Operators (using Operator as constructor argument)

/*
+------------+----------+
| enum value | operator |
+------------+----------+
| INCLUDES   | includes |
| EXCLUDES   | excludes |
| INX        | in       |
| NOT_IN     | not in   |
+------------+----------+
*/
.fromx('account').wherex(new al.SetCondition('x',al.Operator.INCLUDES,new List<Object>{1,2}))
//-> SELECT id FROM account WHERE x INCLUDES (1,2)
.fromx('account').wherex(new al.SetCondition('x',al.Operator.EXCLUDES,new List<Object>{1,2}))
//-> SELECT id FROM account WHERE x EXCLUDES (1,2)
.fromx('account').wherex(new al.SetCondition('x',al.Operator.INX,new List<Object>{1,2}))
//-> SELECT id FROM account WHERE x IN (1,2)
.fromx('account').wherex(new al.SetCondition('x',al.Operator.NOT_IN,new List<Object>{1,2}))
//-> SELECT id FROM account WHERE x NOT IN (1,2)

Set Operators (operator as method identifier)

/*
+-------------------+----------+
| method identifier | operator |
+-------------------+----------+
| includes          | includes |
| excludes          | excludes |
| inx               | in       |
| notin             | not in   |
+-------------------+----------+
*/
.fromx('account').wherex(new al.SetCondition('x').includes(new List<Object>{1,2}))
//-> SELECT id FROM account WHERE x INCLUDES (1,2)
.fromx('account').wherex(new al.SetCondition('x').excludes(new List<Object>{1,2}))
//-> SELECT id FROM account WHERE x EXCLUDES (1,2)
.fromx('account').wherex(new al.SetCondition('x').inx(new List<Object>{1,2}))
//-> SELECT id FROM account WHERE x IN (1,2)
.fromx('account').wherex(new al.SetCondition('x').notIn(new List<Object>{1,2}))
//-> SELECT id FROM account WHERE x NOT IN (1,2)

Primitives to String literals

//null
.fromx('account').wherex(new al.FieldCondition('x').equals(null))
//->SELECT id FROM account WHERE x = null
//Boolean
.fromx('account').wherex(new al.FieldCondition('x').equals(true))
//->SELECT id FROM account WHERE x = true
//String
.fromx('account').wherex(new al.FieldCondition('x').equals('acme'))
//->SELECT id FROM account WHERE x = 'acme'
//Integer
.fromx('account').wherex(new al.FieldCondition('x').equals(1))
//->SELECT id FROM account WHERE x = 1
//Long
.fromx('account').wherex(new al.FieldCondition('x').equals(1L))
//->SELECT id FROM account WHERE x = 1
//Double
.fromx('account').wherex(new al.FieldCondition('x').equals(1.1))
//->SELECT id FROM account WHERE x = 1.1
//Date
.fromx('account').wherex(new al.FieldCondition('x').equals(Date.newinstance(2010,1,1)))
//->SELECT id FROM account WHERE x = 2010-01-01
//Datetime
.fromx('account').wherex(new al.FieldCondition('x').equals(Datetime.newinstance(2010,1,1,1,1,1)))
//->SELECT id FROM account WHERE x = 2010-01-01T01:01:01Z

Date Formulas

//=========================
// Hard-coded day methods
//=========================
.fromx('account').wherex(new al.FieldCondition('CreatedDate',new al.DateFormula().todayx()))
//->SELECT id FROM account WHERE CreatedDate = TODAY
.fromx('account').wherex(new al.FieldCondition('CreatedDate',new al.DateFormula().yesterdayx()))
//->SELECT id FROM account WHERE CreatedDate = YESTERDAY
.fromx('account').wherex(new al.FieldCondition('CreatedDate',new al.DateFormula().tomorrowx()))
//->SELECT id FROM account WHERE CreatedDate = TOMORROW
.fromx('account').wherex(new al.FieldCondition('CreatedDate',new al.DateFormula().last90Days()))
//->SELECT id FROM account WHERE CreatedDate = LAST_90_DAYS
.fromx('account').wherex(new al.FieldCondition('CreatedDate',new al.DateFormula().next90Days()))
//->SELECT id FROM account WHERE CreatedDate = NEXT_90_DAYS
//=========================
// By Units
//=========================
/*
+-----------------------+-----------------+
| UnitOfTime enum value | SOQL equivalent |
+-----------------------+-----------------+
| Day                   | DAY             |
| Week                  | WEEK            |
| Month                 | MONTH           |
| Quarter               | QUARTER         |
| Year                  | FISCAL_QUARTER  |
| FiscalQuarter         | YEAR            |
| FiscalYear            | FISCAL_YEAR     |
+-----------------------+-----------------+
*/
.fromx('account').wherex(new al.FieldCondition('CreatedDate',new al.DateFormula().last(al.UnitOfTime.Day)))
//->SELECT id FROM account WHERE CreatedDate = LAST_N_DAYS:1
.fromx('account').wherex(new al.FieldCondition('CreatedDate',new al.DateFormula().last(al.UnitOfTime.Week)))
//->SELECT id FROM account WHERE CreatedDate = LAST_WEEK
.fromx('account').wherex(new al.FieldCondition('CreatedDate',new al.DateFormula().last(al.UnitOfTime.Month)))
//->SELECT id FROM account WHERE CreatedDate = LAST_MONTH
.fromx('account').wherex(new al.FieldCondition('CreatedDate',new al.DateFormula().last(al.UnitOfTime.Quarter)))
//->SELECT id FROM account WHERE CreatedDate = LAST_QUARTER
.fromx('account').wherex(new al.FieldCondition('CreatedDate',new al.DateFormula().last(al.UnitOfTime.Year)))
//->SELECT id FROM account WHERE CreatedDate = LAST_YEAR
.fromx('account').wherex(new al.FieldCondition('CreatedDate',new al.DateFormula().last(al.UnitOfTime.FiscalQuarter)))
//->SELECT id FROM account WHERE CreatedDate = LAST_FISCAL_QUARTER
.fromx('account').wherex(new al.FieldCondition('CreatedDate',new al.DateFormula().last(al.UnitOfTime.FiscalYear)))
//->SELECT id FROM account WHERE CreatedDate = LAST_FISCAL_YEAR
//=========================
// By Interval
//=========================
.fromx('account').wherex(new al.FieldCondition('CreatedDate',new al.DateFormula().next(al.UnitOfTime.Day)))
//->SELECT id FROM account WHERE CreatedDate = NEXT_N_DAYS:1
.fromx('account').wherex(new al.FieldCondition('CreatedDate',new al.DateFormula().last(al.UnitOfTime.Day)))
//->SELECT id FROM account WHERE CreatedDate = LAST_N_DAYS:1
.fromx('account').wherex(new al.FieldCondition('CreatedDate',new al.DateFormula().next(7,al.UnitOfTime.Day)))
//->SELECT id FROM account WHERE CreatedDate = NEXT_N_DAYS:7
.fromx('account').wherex(new al.FieldCondition('CreatedDate',new al.DateFormula().last(7,al.UnitOfTime.Day)))
//->SELECT id FROM account WHERE CreatedDate = LAST_N_DAYS:7

AND, OR & NOT

//simple AND condition
.fromx('account')
.wherex(
  new al.AndCondition()
   .add(new al.FieldCondition('name','acme'))
   .add(new al.FieldCondition('ispartner',true))
  )
//->SELECT id FROM account WHERE (name = 'acme' AND ispartner = true)
//simple OR condition
.fromx('account')
.wherex(
  new al.OrCondition()
   .add(new al.FieldCondition('name','acme'))
   .add(new al.FieldCondition('ispartner',true))
  )
//->SELECT id FROM account WHERE (name = 'acme' OR ispartner = true)
//simple NOT condition
.fromx('account')
.wherex(
  new al.NotCondition(new al.AndCondition()
   .add(new al.FieldCondition('name','acme'))
   .add(new al.FieldCondition('ispartner',true)))
  )
//->SELECT id FROM account WHERE NOT((name = 'acme' AND ispartner = true))
//nested ANDs and ORs
.fromx('account')
.wherex(
    new al.NotCondition(
        new al.AndCondition()
        .add(
            new al.OrCondition()
            .add(new al.FieldCondition('name','acme'))
            .add(
                new al.AndCondition()
                .add(new al.FieldCondition('ispartner',true))
                .add(new al.FieldCondition('NumberOfEmployees').lessThan(10))
            )
        )
        .add(
            new al.OrCondition()
            .add(new al.FieldCondition('createddate').lessThan(new al.DateFormula().yesterdayx()))
            .add(new al.FieldCondition('Rating','Hot'))
        )
    )
)
//->SELECT id FROM account WHERE NOT(((name = 'acme' OR (ispartner = true AND NumberOfEmployees < 10)) AND (createddate < YESTERDAY OR Rating = 'Hot')))



ORDER BY



Single Order By

/*
You can create an OrderBy using the following formats:
new al.OrderBy(fieldName).[ascending|descending|nullsFirst|nullsLast]*()
*/
.fromx('account').orderByx(new al.OrderBy('name'))
//->SELECT id FROM account ORDER BY name
.fromx('account').orderByx(new al.OrderBy('name').ascending().nullsFirst())
//->SELECT id FROM account ORDER BY name ASC NULLS FIRST
.fromx('account').orderByx(new al.OrderBy('name').ascending().nullsLast())
//->SELECT id FROM account ORDER BY name ASC NULLS FIRST
.fromx('account').orderByx(new al.OrderBy('name').descending().nullsFirst())
//->SELECT id FROM account ORDER BY name DESC NULLS FIRST
.fromx('account').orderByx(new al.OrderBy('name').descending().nullsLast())
//->SELECT id FROM account ORDER BY name DESC NULLS FIRST

Multiple Order By

.fromx('account').orderByx(new List<al.OrderBy>{
  new al.OrderBy('name').ascending().nullsFirst()
  ,new al.OrderBy('rating').descending().nullsLast()
})
//->SELECT id FROM account ORDER BY name ASC NULLS FIRST, rating DESC NULLS LAST



LIMIT



.fromx('account').limitx(50)
//->SELECT id FROM account LIMIT 50



SOQL Options for toSoql() method



Wildcards

Enabled by default: No

//default
.fromx('account')
.wherex(
  new al.OrCondition()
  .add(new al.FieldCondition('name').likex('acme'))
  .add(new al.FieldCondition('name').likex('test'))
).toSoql()
//->SELECT id FROM account WHERE (name like 'acme' OR name like 'test')
.fromx('account')
.wherex(
  new al.OrCondition()
  .add(new al.FieldCondition('name').likex('acme'))
  .add(new al.FieldCondition('name').likex('test'))
).toSoql(new al.SoqlOptions().wildcardStringsInLikeOperators())
//->SELECT id FROM account WHERE (name like '%acme%' OR name like '%test%')
.fromx('account')
.wherex(
  new al.OrCondition()
  .add(new al.FieldCondition('name').likex('acme'))
  .add(new al.FieldCondition('name').likex('test'))
).toSoql(new al.SoqlOptions().doNotWildcardStringsInLikeOperators())
//->SELECT id FROM account WHERE (name like 'acme' OR name like 'test')

String Escaping

Enabled by default: Yes

//GOOD (default)
.fromx('account')
.wherex(new al.FieldCondition('name').likex('O\'Neal'))
.toSoql()
//->SELECT id FROM account WHERE name like 'O\'Neal'
//BAD!  The generated query below is invalid and will throw an error.
//Why even allow it as an option?  Because you never know when it might be needed - invalid or not.
.fromx('account')
.wherex(new al.FieldCondition('name').likex('O\'Neal'))
.toSoql(new al.SoqlOptions().doNotEscapeSingleQuotes())
//->SELECT id FROM account WHERE name like 'O'Neal'
.fromx('account')
.wherex(new al.FieldCondition('name').likex('O\'Neal'))
.toSoql(new al.SoqlOptions().escapeSingleQuotes())
//->SELECT id FROM account WHERE name like 'O\'Neal'

Vote for my idea: Explain event which caused Org Admin Lock

VisualForce Pagination with apex-lang

Pagination in VisualForce is a frequently occurring requirement for force.com developers. While the platform includes a native api for pagination in the StandardSetController class, it’s fairly inflexible; especially for complex pagination. And just as important, the native api supports pagination with sObjects only, so if you want to show pages of “plain old apex objects”, you’re out of luck. (And in case you didn’t know, sObjects are NOT Objects in apex. This is very different from Java in that all classes inherit from Object in Java.)

UPDATE:  Starting in Spring ‘10, an sObject can be referred to as an Object.

In this blog entry, I’ll introduce you to pagination in apex-lang via a concept called “paginators”. I’ll describe the design and then go through several examples of varying levels of difficulty which demonstrate how to effectively utilize a paginator.

There are two types of paginators in apex-lang, one for sObjects (SObjectPaginator) and one for “plain old apex objects (ObjectPaginator). The classes are essentially mirrors of each other; however, the redundancy is necessary (unfortunately) due to the fact that sObjects are not Objects in apex.

Once a paginator is constructed, your code will need to call the all-important setRecords() method in order to populate the paginator with data. Now comes the key part. The setRecords() method will invoke a handleNewPage() method on any “listeners” of the paginator. This means you’ll need to implement a handleNewPage() method in your code (and implement corresponding interface ObjectPaginatorListener or SObjectPaginatorListener) in order to receive page changes. The beauty of this design is the handleNewPage() method will also be called for user triggered events. These include the user clicking on standard pagination actions such as next, previous, last, etc. Paginators have these methods built-in and those methods can be bound directly on your page. Below is a sequence diagram which illustrates the interaction between the VisualForce page, controller, and paginator.

PaginatorInteraction

Note: It might seem you should be able to bind directly to the paginator’s page variable and implementing the handlePageChange method should be correspondingly optional as well. However, there’s another unfortunate Apex/VisualForce feature which prevents a VisualForce page from binding directly to the page variable on a paginator. To illustrate the issue, the following page & controller fails to execute.

1.  public class MyController{
2.      public List records {get;set;}
3.      public MyController(){
4.          records = [select id,name,industry from Account limit 100];
5.      }
6.  }
7.
8.  <apex:page>
9.      <apex:repeat value="{!records}" var="record">
10.         <apex:outputText value="{!record.industry}"><br/>
11.     </apex:repeat>
12. </apex:page>

The failure occurs at run-time on line 10 since record is of type sObject. sObjects do not contain a property called industry so the page fails. This means that to bind directly to named properties, your record must be of a concrete type. This necessitates the need for having code which uses a paginator to implement the handlePageChange() method. In this method, your code will need to perform a down-cast; the casting stinks but there’s really no other generic way of handling this.

On to the code examples!

First, let’s start with just about the simplest example possible. The below controller runs a SOQL query on Account and divides the results into pages of 15 records each via SObjectPaginator. The handlePageChange() method is called by the paginator as part of the setRecords() invocation as well as when the user clicks on the Next and Previous links.

Demo: http://rvdemo-developer-edition.na6.force.com/AccountPaginationDemo

<!-- ======================================================= -->
<!-- Controller -->
global class AccountPaginationDemo implements SObjectPaginatorListener {
	global List<Account> accounts {get;private set;}
	global SObjectPaginator paginator {get;private set;}
	global AccountPaginationDemo(){
		accounts = new List<Account>();
		//15 is pageSize, this refers to this class which acts as listener to paginator
		paginator = new SObjectPaginator(5,this);
		paginator.setRecords([select id,name from Account limit 100]);
	}
	global void handlePageChange(List<SObject> newPage){
		accounts.clear();
		if(newPage != null){
			for(SObject acct : newPage){
				accounts.add((Account)acct);
			}
		}
	}
}
<!-- Page: page -->
<apex:page showHeader="false" sidebar="false" standardStylesheets="true" controller="AccountPaginationDemo">
	<apex:composition template="DemoTemplate">
		<apex:define name="body">
			<apex:form >
			    <apex:pageBlock title="Accounts" id="accounts">
			        <apex:pageBlockTable value="{!accounts}" var="account">
						<apex:column >
							<apex:facet name="header">Name</apex:facet>
							<apex:outputPanel >{!account.name}</apex:outputPanel>
						</apex:column>
						<apex:facet name="footer">
							<apex:outputPanel >
								<apex:outputText value="Page {!paginator.pageNumberDisplayFriendly} of {!paginator.pageCount} in {!paginator.recordCount} Results"/>
								<apex:outputPanel >    </apex:outputPanel>
								<apex:commandLink value="Previous" action="{!paginator.previous}"
									rendered="{!IF(paginator.hasPrevious,'true','false')}"/>
								<apex:outputText value="Previous" rendered="{!IF(NOT(paginator.hasPrevious),'true','false')}"/>
								<apex:outputPanel > | </apex:outputPanel>
								<apex:commandLink value="Next" action="{!paginator.next}"
									rendered="{!IF(paginator.hasNext,'true','false')}"/>
								<apex:outputText value="Next" rendered="{!IF(NOT(paginator.hasNext),'true','false')}"/>
							</apex:outputPanel>
						</apex:facet>
			        </apex:pageBlockTable>
			    </apex:pageBlock>
			</apex:form>
		</apex:define>
	</apex:composition>
</apex:page>

The next example shows how a “run-time” property can be added to an sObject and the same basic paginator interface can be utilized via the Object paginator version as opposed to the sObject version. In the below controller, a “plain old apex object” called SelectableAccount is used to store both an Account and a Boolean flag representing whether or not the Account is selected (i.e. the “run-time” property). Instead of creating an SObjectPaginator, this example converts the retrieved Accounts into SelectableAccounts and creates an ObjectPaginator instead.

Demo: http://rvdemo-developer-edition.na6.force.com/SelectableAccountPaginationDemo

<!-- ======================================================= -->
<!-- Controller -->
global class SelectableAccountPaginationDemo implements ObjectPaginatorListener {
	global List<SelectableAccount> accounts {get;private set;}
	global ObjectPaginator paginator {get;private set;}
	global SelectableAccountPaginationDemo(){
		this.accounts = new List<SelectableAccount>();
		List<SelectableAccount> all = new List<SelectableAccount>();
		List<Account> records = [select id,name from Account limit 100];
		if(records != null){
			for(Account acct : records){
				all.add(new SelectableAccount(acct));
			}
		}
		//15 is pageSize, this refers to this class which acts as listener to paginator
		paginator = new ObjectPaginator(5,this);
		paginator.setRecords(all);
	}
	global void handlePageChange(List<Object> newPage){
		accounts.clear();
		if(newPage != null){
			for(Object acct : newPage){
				accounts.add((SelectableAccount)acct);
			}
		}
	}
	global class SelectableAccount{
		global Boolean selected{get;set;}
		global Account obj{get;set;}
		global SelectableAccount(Account obj){
			this.obj = obj;
		}
	}
}
<!-- Page: page -->
<apex:page showHeader="false" sidebar="false" standardStylesheets="true" controller="SelectableAccountPaginationDemo">
	<apex:composition template="DemoTemplate">
		<apex:define name="body">
			<apex:form >
			    <apex:pageBlock title="Accounts" id="accounts">
			        <apex:pageBlockTable value="{!accounts}" var="account">
						<apex:column >
							<apex:inputCheckbox value="{!account.selected}"/>
						</apex:column>
						<apex:column >
							<apex:facet name="header">Name</apex:facet>
							<apex:outputPanel >{!account.obj.name}</apex:outputPanel>
						</apex:column>
						<apex:facet name="footer">
							<apex:outputPanel >
								<apex:outputText value="Page {!paginator.pageNumberDisplayFriendly} of {!paginator.pageCount} in {!paginator.recordCount} Results"/>
								<apex:outputPanel >    </apex:outputPanel>
								<apex:commandLink value="Previous" action="{!paginator.previous}"
									rendered="{!IF(paginator.hasPrevious,'true','false')}"/>
								<apex:outputText value="Previous" rendered="{!IF(NOT(paginator.hasPrevious),'true','false')}"/>
								<apex:outputPanel > | </apex:outputPanel>
								<apex:commandLink value="Next" action="{!paginator.next}"
									rendered="{!IF(paginator.hasNext,'true','false')}"/>
								<apex:outputText value="Next" rendered="{!IF(NOT(paginator.hasNext),'true','false')}"/>
							</apex:outputPanel>
						</apex:facet>
			        </apex:pageBlockTable>
			    </apex:pageBlock>
			</apex:form>
		</apex:define>
	</apex:composition>
</apex:page>

The next and final example is quite a bit more complicated. The example allows browsing of all accounts and contacts. There are two result sets: an Account result set and a Contact result set. The currently selected Account and Contact is in bold and the corresponding record’s details are shown below. In essence, this is a “quick” view screen.

Demo: http://rvdemo-developer-edition.na6.force.com/PaginatorDemo

<!-- ======================================================= -->
global class PaginatorDemo {
	public List<AccountWrapper> accounts {get;set;}
	public SObjectPaginator acctPaginator{get;set;}
	public Account selectedAccount{get;set;}
	public List<ContactWrapper> contacts {get;set;}
	public SObjectPaginator contPaginator{get;set;}
	public Contact selectedContact{get;set;}

	public PaginatorDemo(){
		this.accounts = new List<AccountWrapper>();
		this.contacts = new List<ContactWrapper>();
		this.acctPaginator = new SObjectPaginator(5,new AccountListListener(this));
		this.contPaginator = new SObjectPaginator(5,new ContactListListener(this));
		this.acctPaginator.setRecords([select id,name from account]);
	}

	global void handleAccountListPageChange(List<SObject> newPage){
		this.accounts.clear();
		if(newPage != null && newPage.size() > 0){
			for(Integer i = 0; i < newpage.size(); i++){
				AccountWrapper acct = new AccountWrapper((Account)newPage.get(i));
				accounts.add(acct);
				acct.serialNumber = i + acctPaginator.pageStartPosition;
			}
			PageUtils.param('accountId',accounts.get(0).obj.id);
			handleAccountSelected();
		}
	}

	public PageReference handleAccountSelected(){
		String accountId = PageUtils.param('accountId');
		for(AccountWrapper acct : accounts){
			acct.selected = acct.obj.id == accountId;
			if(acct.selected){
				selectedAccount = acct.obj;
				this.contPaginator.setRecords([select id,name from contact where accountid = :acct.obj.id]);
			}
		}
		return null;
	}

	global void handleContactListPageChange(List<SObject> newPage){
		System.debug('new contact list page: ' + ArrayUtils.toString(newPage));
		this.contacts.clear();
		if(newPage != null && newPage.size() > 0){
			for(Integer i = 0; i < newpage.size(); i++){
				ContactWrapper cntct = new ContactWrapper((Contact)newPage.get(i));
				contacts.add(cntct);
				cntct.serialNumber = i + (contPaginator == null ? 0 : contPaginator.pageStartPosition);
			}
			Contact wrapper = (Contact)this.contacts.get(0).obj;
			if(wrapper != null){
				PageUtils.param('contactId',wrapper.id);
				handleContactSelected();
			}
		}
	}

	public PageReference handleContactSelected(){
		String contactId = PageUtils.param('contactId');
		for(ContactWrapper contact : contacts){
			contact.selected = contact.obj.id == contactId;
			if(contact.selected){
				selectedContact = contact.obj;
			}
		}
		return null;
	}

	global class AccountListListener implements SObjectPaginatorListener {
		private PaginatorDemo controller;
		global AccountListListener(PaginatorDemo controller){
			this.controller = controller;
		}
		global void handlePageChange(List<SObject> newPage){
			controller.handleAccountListPageChange(newPage);
		}
	}

	global class ContactListListener implements SObjectPaginatorListener {
		private PaginatorDemo controller;
		global ContactListListener(PaginatorDemo controller){
			this.controller = controller;
		}
		global void handlePageChange(List<SObject> newPage){
			controller.handleContactListPageChange(newPage);
		}
	}

	public class AccountWrapper{
		public Account obj{get;set;}
		public Integer serialNumber{get;set;}
		public Boolean selected{get;set;}
		public AccountWrapper(Account obj){
			this.obj = obj;
		}
	}

	public class ContactWrapper{
		public Contact obj{get;set;}
		public Integer serialNumber{get;set;}
		public Boolean selected{get;set;}
		public ContactWrapper(Contact obj){
			this.obj = obj;
		}
	}
}
<!-- ======================================================= -->
<apex:page showHeader="false" sidebar="false" standardStylesheets="true" controller="PaginatorDemo">
	<apex:form >
		<p>
			<apex:actionStatus startStyle="color: #F00; font-weight: bold;" startText="Updating...." stopText="" id="updateStatus"/>
		</p>
		<table width="100%" border="0" cellpadding="3" cellspacing="0">
			<tr>
				<td valign="top" width="50%">
				    <apex:pageBlock title="Accounts {!acctPaginator.pageStartPositionDisplayFriendly} - {!acctPaginator.pageEndPositionDisplayFriendly} of {!acctPaginator.recordCount}" id="accounts">
				        <apex:pageBlockTable value="{!accounts}" var="account">
							<apex:column >
								<apex:facet name="header">#</apex:facet>
								<apex:outputText value="{!account.serialNumber+1}"/>
							</apex:column>
							<apex:column >
								<apex:facet name="header">Name</apex:facet>
								<apex:outputPanel rendered="{!account.selected}"><b>{!account.obj.name}</b></apex:outputPanel>
								<apex:commandLink rendered="{!NOT(account.selected)}" action="{!handleAccountSelected}" value="{!account.obj.name}"
									 reRender="accounts,contacts,accountDetail,contactDetail" status="updateStatus">
									<apex:param name="accountId" value="{!account.obj.id}"/>
								</apex:commandLink>
							</apex:column>
							<apex:facet name="footer">
								<apex:outputPanel >
									<apex:commandLink action="{!acctPaginator.first}" value="<< First"
										reRender="accounts,contacts,accountDetail,contactDetail" status="updateStatus"/>

									<apex:outputPanel > | </apex:outputPanel>
									<apex:commandLink action="{!acctPaginator.previous}" rendered="{!acctPaginator.hasPrevious}"
										value="< Previous" reRender="accounts,contacts,accountDetail,contactDetail" status="updateStatus"/>
									<apex:outputText rendered="{!NOT(acctPaginator.hasPrevious)}"
										value="< Previous"/>

									<apex:outputPanel > | </apex:outputPanel>

									<apex:commandLink action="{!acctPaginator.next}" rendered="{!acctPaginator.hasNext}"
										value="Next >" reRender="accounts,contacts,accountDetail,contactDetail" status="updateStatus"/>
									<apex:outputText rendered="{!NOT(acctPaginator.hasNext)}"
										value="Next >" />

									<apex:outputPanel > | </apex:outputPanel>

									<apex:commandLink action="{!acctPaginator.last}" value="Last >>" reRender="accounts,contacts,accountDetail,contactDetail"
										status="updateStatus"/>
								</apex:outputPanel>
							</apex:facet>
				        </apex:pageBlockTable>
				    </apex:pageBlock>
					<apex:outputPanel id="accountDetail">
						<apex:detail subject="{!selectedAccount.id}" relatedList="false" title="false"/>
					</apex:outputPanel>
				</td>
				<td valign="top" width="50%">
				    <apex:pageBlock title="Contacts {!contPaginator.pageStartPositionDisplayFriendly} - {!contPaginator.pageEndPositionDisplayFriendly} of {!contPaginator.recordCount}" id="contacts">
				        <apex:pageBlockTable value="{!contacts}" var="contact">
							<apex:column >
								<apex:facet name="header">#</apex:facet>
								<apex:outputText value="{!contact.serialNumber+1}"/>
							</apex:column>
							<apex:column >
								<apex:facet name="header">Name</apex:facet>
								<apex:outputPanel rendered="{!contact.selected}"><b>{!contact.obj.name}</b></apex:outputPanel>
								<apex:commandLink rendered="{!NOT(contact.selected)}" action="{!handleContactSelected}" value="{!contact.obj.name}"
									 reRender="contacts,contactDetail" status="updateStatus">
									<apex:param name="contactId" value="{!contact.obj.id}"/>
								</apex:commandLink>
							</apex:column>
							<apex:facet name="footer">
								<apex:outputPanel id="contactsLinks">
									<apex:commandLink action="{!contPaginator.first}" value="<< First"
										reRender="contacts,contactDetail" status="updateStatus"/>

									<apex:outputPanel > | </apex:outputPanel>
									<apex:commandLink action="{!contPaginator.previous}" rendered="{!contPaginator.hasPrevious}"
										value="< Previous" reRender="contacts,contactDetail" status="updateStatus"/>
									<apex:outputText rendered="{!NOT(contPaginator.hasPrevious)}"
										value="< Previous"/>

									<apex:outputPanel > | </apex:outputPanel>

									<apex:commandLink action="{!contPaginator.next}" rendered="{!contPaginator.hasNext}"
										value="Next >" reRender="contacts,contactDetail" status="updateStatus"/>
									<apex:outputText rendered="{!NOT(contPaginator.hasNext)}"
										value="Next >" />

									<apex:outputPanel > | </apex:outputPanel>

									<apex:commandLink action="{!contPaginator.last}" value="Last >>" reRender="contacts,contactDetail"
										status="updateStatus"/>
								</apex:outputPanel>
							</apex:facet>
				        </apex:pageBlockTable>
				    </apex:pageBlock>
					<apex:outputPanel id="contactDetail">
						<apex:detail subject="{!selectedContact.id}" relatedList="false" title="false"/>
					</apex:outputPanel>
				</td>
			</tr>
		</table>

	</apex:form>
</apex:page>