How to change variable value on demand in JasperReports

Saquibul Islam Waheed picture Saquibul Islam Waheed · Aug 14, 2013 · Viewed 6.9k times · Source

I am working with iReport. Here is the situation:

I have some parameters named branchID, spType.

I have created one variable named branchName (string) which is by default null.

What I need to do is, to change/ edit the value of the variable branchName depending on the values of branchID and spType

How can I do this with JasperReports using If Else. Is it something with the properties of the variable branchName? Any help/ Suggestion would be highly appreciated.

Answer

Kahini Wadhawan picture Kahini Wadhawan · Aug 14, 2013

Expressions Scripting Language in Jasper reports is your friend!

What i can fathom from your query is that you want to compute the value of a variable based on values of two parameters. In short, you want to do something like:-

Simple if-else

If (branchId == 1 && spType == "abc") 
     branchName = "Xyz1";
 else 
     branchName = "Xyz2";

In Jasper scripting language, the above expression can be written as :-

($P{branchId}==1 && 
 $P{spType} != null &&
 $P{spType}.equals("abc"))?"Xyz1":"Xyz2"

Nested If-else

If (branchId == 1 && spType == "abc") 
    branchName = "Xyz1";
 else if (branchId = 2 && spType == "def")
    branchName = "Xyz2"; 
 else 
    branchName = "Xyz3";

Jasper expression:

( $P{branchId} ==1 &&
  $P{spType} !=null && 
  $P{spType}.equals("abc") ) ? "Xyz1" :
    (($P{branchId} == 2 &&
      $P{spType} != null &&
      $P{spType}.equals("def")) ? "Xyz2" : "Xyz3");

For more details, have a look at this tutorial: http://www.tutorialspoint.com/jasper_reports/jasper_report_expression.htm

Here is a similar stackoverflow question also: doing comparison if else in JasperReports

For core concept, Page no. 10 of this pdf: http://jasperreports.sourceforge.net/JasperReports-Ultimate-Guide-3.pdf