Monday, November 28, 2011

Crystal Reports : Offloading Selection Logic into a Formula

Here is a nice technique to use when your selection criteria starts to get out of control; offload the "heavy lifting" to a formula, then just reference that formula within the Selection Expert.

For instance, let us imagine our Selection Criteria needs to test for multiple things; {CONTACT.STATE} should be either NY, PA or NJ, AND {CONTACT.SOURCE} should be "XMAS 2011" AND {CONTACT.LASTESTIMATE} is at least $100 but no more then $500.

Now, the Selection Criteria for that would look something like this;
{CONTACT.STATE} IN ['PA', 'NY'] AND {CONTACT.SOURCE} LIKE "*XMAS 2011*"
AND
({CONTACT.LASTESTIMATE} >= 100 AND {CONTACT.LASTESTIMATE} <= 500)

Note the use of enclosing parenthesis around the last two conditions; we want the LASTESTIMATE to be BOTH greater than 100 and less than 500.

But you are a Crystal Reporter, and know deep in your heart that someday, someone will need you to change this report. Here is how I would handle the same situation; I would create a separate formula for each condition, thusly;

{@frmState}
IF {CONTACT.STATE} IN ['PA', 'NY'] THEN TRUE ELSE FALSE

{@frmSource}
IF {CONTACT.SOURCE} LIKE "*XMAS 2011*" THEN TRUE ELSE FALSE

{@frmEstimate}
IF {CONTACT.LASTESTIMATE} >= 100 AND {CONTACT.LASTESTIMATE} <= 500 THEN TRUE ELSE FALSE

Now, once those formulas are created (and can be viewed right within the report itself, making troubleshooting very easy), you can use them in the Selection Criteria like this;

{@frmState} = TRUE AND {@frmSource} = TRUE AND {@frmEstimate} = TRUE

This leaves lots of room for compounding, making changes, and plugging in the eventual Parameters. Try it!

No comments: