Search code examples
jasper-reports

How to get report_count from subreport in iReport


I have a sub report in my main report .

I need to hide a text if sub report returns no rows.

I tried to get the number of records of subreport adding a new variable in main report and setting it as destination variable in return values property of subreport(for rount_count), but when I run the main report, the value of variable is null


Solution

  • To count the record's in subreport

    1. Define a variable in main report

      <variable name="subReportCount" class="java.lang.Integer"/>
      
    2. When calling subreport set the return parameter to you variable

      <subreport>
          <reportElement x="100" y="20" width="400" height="20" uuid="a7a89ebb-54d4-4b6e-8c9f-c107e8a40bbb"/>
          <dataSourceExpression><![CDATA[... your datasource ...]]></dataSourceExpression>
          <returnValue subreportVariable="REPORT_COUNT" toVariable="subReportCount"/>
          <subreportExpression><![CDATA[$P{SUBREPORT_DIR} + "Your_subreport.jasper"]]></subreportExpression>
      </subreport>
      

    This variable can now be used in a textField, however you need to be careful since the textField need's to be evaluate at the correct time (after subreport has been executed).

    The property on the textField is evaluationTime

    Example

    <textField evaluationTime="Report" pattern="###0">
        <reportElement positionType="Float" x="300" y="60" width="200" height="20" uuid="125aa2d0-3d4e-4377-bed1-b4531c9142c9"/>
        <textElement textAlignment="Right" verticalAlignment="Middle"/>
        <textFieldExpression><![CDATA[$V{subReportCount}]]></textFieldExpression>
    </textField>
    

    Evaluation time:

    Auto Evaluation time indicating that each variable participating in the expression should be evaluated at a time decided by the engine.
    Band The element will be evaluated at band end.
    Column A constant specifying that an expression should be evaluated after each column is filled.
    Group A constant specifying that an expression should be evaluated after each group break.
    Master Used for elements that are evaluated at the moment the master report ends.
    Now A constant specifying that an expression should be evaluated at the exact moment in the filling process when it is encountered.
    Page A constant specifying that an expression should be evaluated after each page is filled.
    Report A constant specifying that an expression should be evaluated at the end of the filling process.

    In general when using subreport

    • if it is in detail band and is repeated on datasource set evalutationTime="Band"
    • if it's present only one set evalutationTime="Report"