Vous êtes sur la page 1sur 692

Tally Technology

The Complete Reference


The information contained in this document represents the current view of Tally Solutions Pvt. Ltd., (‘Tally’
in short) on the topics discussed as of the date of publication. Because Tally must respond to changing
market conditions, it should not be interpreted to be a commitment on the part of Tally, and Tally cannot
guarantee the accuracy of any information presented after the date of publication.

This document is for informational purposes only. TALLY MAKES NO WARRANTIES, EXPRESS OR
IMPLIED, IN THIS DOCUMENT.

Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights
under copyright, no part of this document may be reproduced, stored in, or introduced into a retrieval
system, or transmitted in any form, by any means (electronic, mechanical, photocopying, recording, or
otherwise), or for any purpose, without the express written permission of Tally Solutions Pvt. Ltd.

Tally may have patents, patent applications, trademarks, copyrights, or other intellectual property rights
covering subject matter in this document. Except as expressly provided in any written licence agreement
from Tally, the furnishing of this document does not give you any licence to these patents, trademarks,
copyrights, or other intellectual property.

© 2011 Tally Solutions Pvt. Ltd. All rights reserved.

Tally, Tally 9, Tally9, Tally.ERP, Tally.ERP 9, Shoper, Shoper 9, Shoper POS, Shoper HO, Shoper 9 POS,
Shoper 9 HO, TallyDeveloper, Tally Developer, Tally.Developer 9, Tally.NET, Tally Development
Environment, Tally Extender, Tally Integrator, Tally Integrated Network, Tally Service Partner,
TallyAcademy & Power of Simplicity are either registered trademarks or trademarks of Tally Solutions Pvt.
Ltd. in India and/or other countries. All other trademarks are properties of their respective owners.

Version: Tally Technology – The Complete Reference/1.0/September 2011


Preface
This is an era of Domain Specific Languages(DSL’s). Well-designed DSL’s have been quite
valuable with programmers operating in a specific domain. These prove particularly worth-
while from the point of view of improvements in productivity and faster implementation
cycles.

The heart and crux of Tally Technology is the DSL-Tally Definition Language (TDL) which
has been there from the advent of Tally version 5.4 during the late 90’s i.e., around 1995-96.
The language used in development of Tally, predominantly made its presence felt with
business programmers who opted for developing customizations and extensions on Tally.
Over the years, major advancements in Tally Technology resulted in transformation of Tally as
a complete Application Development Platform. The developments in TDL resulted in capabil-
ities for Rapid Development, Rendering, Data Management and Integration. The Tally Defini-
tion Language (TDL) along with the development suite Tally.Developer 9 (TD 9) provides the
strong technology backbone for developing solutions on Tally platform.

This book provides a comprehensive coverage of Tally Technology starting from the basic
understanding of Tally Architechture to in-depth concepts, usage and implementation
scenarios using TDL. With each chapter you will find explanations for topics along with
syntax and examples substantiating the content. The exercises provided give a good hands-on
experience for the concepts learnt.

The preliminary chapters from 1 through 5 mainly focus on the various components of the
language along with User Interface Design elements. The chapters 6 through 11 provide the
core capability coverage on the basis of which Tally is termed as an “Application Develop-
ment Platform”. The chapters “6. Objects, Collections and Internal Object Structure”,
“8. Object Manipulation and Storage” and “11. User Defined Fields, Validation and Controls”
emphasizes solely on data storage, manipulation and retrieval methodologies using the user
interface. The chapters “7. Actions, Event Framework and Key Definition“ and “9. TDL Pro-
cedural Capabilities“ cover concepts which make TDL a true action and event driven language
with procedural capabilities augmenting its power. The chapter “10. Variable Framework“
helps in understanding the usage of various types of variables available in TDL. The chapter
“12. Advanced Reporting and Printing” will take you through the various reporting and
printing techniques. The various techniques aid in development of simple tabular reports to
complex columnar reports which provide a strong foundation in the area of MIS reporting.

Towards the end you will find various use cases which will give you an insight on various
implementation scenarios emphasizing on the application of concepts covered. By the time
you complete the book you are ready to undertake the project work “Inventory Management-
Garment Store” and dive into the over expansive world of Tally Technology.
Contents
Chapter 1: Tally Technology – An Overall Perspective
1.1 Introduction...................................................................................................................... 1
1.2 Need for Tally Extensions .......................................................................................................... 2
1.3 The Domain Specific Language – TDL ................................................................................... 4
1.3.1 Definition Language .......................................................................................................... 4
1.3.2 Action Driven Language with Procedural Capabilities .................................................... 4
1.3.3 Completely Object Oriented .............................................................................................. 4
1.4 Tally – As a Development Platform ......................................................................................... 5
1.4.1 Rapid Development ............................................................................................................ 5
1.4.2 Flexibility ........................................................................................................................... 5
1.5 Components of a TDL program .............................................................................................. 6
1.5.1 Underlying Tally Technology ............................................................................................ 7
1.6 Tally Architecture – Overview ................................................................................................. 8
1.6.1 The Application/Tally Layer .............................................................................................. 9
1.6.2 The TDL Language and Interpreter Layer ........................................................................ 9
1.6.3 Platform Layer ................................................................................................................... 9
1.7 Tally Technology – Capabilities ............................................................................................. 11
1.7.1 Solution-ability & Customizability .................................................................................. 11
1.7.2 Multiple Output Capability .............................................................................................. 11
1.7.3 Data Management Capability .......................................................................................... 11
1.7.4 Integrate-ability ............................................................................................................... 11
1.8 Tally Development Environment ............................................................................................ 12
1.8.1 Getting Started with TD 9 ................................................................................................ 13
1.8.2 Usage of Different Explorer Windows ............................................................................. 14
1.8.3 Usage of different Browsers and Property Window ........................................................ 15
1.8.4 Coding Convention .......................................................................................................... 16
1.8.5 Navigating and understanding the Tally Source Code(Default TDL project) ................. 16
1.8.6 Folder Structure and File naming convention ................................................................. 17
1.8.7 Navigating and Searching project Default TDL .............................................................. 17
1.9 TDL Program Life Cycle ......................................................................................................... 17

Chapter 2: Definitions, Attributes and Modifiers


2.1 Definitions .................................................................................................................................. 23
2.1.1 Definition Categorization ................................................................................................ 24
2.2 Attributes ..................................................................................................................................... 32
2.2.1 List Type Attribute ............................................................................................................ 33
2.2.2 Attribute Feature – Discreteness ..................................................................................... 34
2.2.3 Classification of Attributes .............................................................................................. 34
2.2.4 Predefined Attribute values in TDL ................................................................................. 39
2.2.5 Modifiers .......................................................................................................................... 41

i
Contents

Chapter 3: Datatypes, Operators and Expressions


3.1 Introduction ................................................................................................................................ 55
3.2 Data Types ..................................................................................................................... 55
3.2.1 Simple Data Types ........................................................................................................... 56
3.2.2 Compound Data Type ...................................................................................................... 57
3.2.3 Data Conversion (Type Casting) ..................................................................................... 64
3.3 Operators in TDL ...................................................................................................................... 70
3.3.1 Unary Operators .............................................................................................................. 70
3.3.2 Arithmetic Operators ....................................................................................................... 71
3.3.3 Logical Operators ............................................................................................................ 72
3.3.4 Comparison Operators .................................................................................................... 75
3.3.5 String Operators .............................................................................................................. 76
3.3.6 Operator Precedence ....................................................................................................... 77
3.3.7 Data Types supported by Arithmetic Operators .............................................................. 78
3.4 Expressions in TDL .................................................................................................................. 82

Chapter 4: Access Specifiers and Special Symbols


4.1 Access Specifiers ....................................................................................................................... 84
4.1.1
Usage of @ and @@ ....................................................................................................... 84
4.1.2
Naming Conventions for Formulae ................................................................................. 84
4.1.3
Classification of Formulae .............................................................................................. 84
4.1.4
Accessing a Local Formula using @ ............................................................................... 84
4.1.5
Accessing of Global Formula using @@ ........................................................................ 85
4.1.6
The Usage of # ................................................................................................................. 86
4.1.7
The Usage of ## ............................................................................................................... 86
4.1.8
Usage of $ and $$ ............................................................................................................ 90
4.2 Overview of a Method .............................................................................................................. 90
4.3 Functions in TDL ...................................................................................................................... 91
4.3.1 Accessing a Function using $$ ....................................................................................... 91
4.4 Frequently used functions in TDL .......................................................................................... 99
4.4.1
Type Casting Functions ................................................................................................... 99
4.4.2
Mathematical Functions ................................................................................................ 101
4.4.3
Logical Functions .......................................................................................................... 102
4.4.4
Date Functions ............................................................................................................... 104
4.5 Special Symbols ...................................................................................................................... 108
4.5.1 Usage as Definition Modifiers ....................................................................................... 108
4.5.2 Usage as Code Differentiators ...................................................................................... 110
4.5.3 Usage in ODBC Context ................................................................................................ 112
4.6 Valid Expressions in TDL ..................................................................................................... 113

Chapter 5: Dimensions, Formatting and Report Layouts


5.1 Introduction .............................................................................................................................. 117
5.2 Unit of Measurement .............................................................................................................. 117
5.3 Dimensional Attributes .......................................................................................................... 118

ii
Contents

5.3.1
Sizing/ Size Attributes .................................................................................................... 118
5.3.2
Spacing/ Position Attributes .......................................................................................... 125
5.3.3
Alignment Attributes ...................................................................................................... 130
5.3.4
Some Specific Attributes ................................................................................................ 145
5.4 Definitions and Attributes for Formatting ........................................................................... 149
5.4.1 Border ............................................................................................................................ 149
5.4.2 Color, Background, PrintFG and PrintBG Attribute .................................................... 156
5.4.3 Format Attribute ............................................................................................................ 157
5.5 Report Layouts in Tally.ERP 9 ............................................................................................. 159
5.5.1 Tabular Report – Eg: Ledger Vouchers ......................................................................... 159
5.5.2 Columnar Report, Eg: Sales Register .......................................................................... 160
5.5.3 Designing a Hierarchical Report, Eg: Trial Balance ................................................... 161

Chapter 6: Objects, Collections and Internal Object Structure


6.1 Introduction .............................................................................................................................. 163
6.2 Objects – In General ............................................................................................................... 163
6.2.1 Tally Object Structure .................................................................................................... 164
6.2.2 Object Types ................................................................................................................... 166
6.3 Collections ................................................................................................................................ 168
6.3.1 Simple and Compound Collection ................................................................................. 169
6.3.2 Populating a Collection ................................................................................................. 169
6.3.3 Dynamic Objects ............................................................................................................ 179
6.4 Methods ..................................................................................................................................... 184
6.4.1 Internal Methods ............................................................................................................ 184
6.4.2 User Defined / External Methods .................................................................................. 185
6.4.3 Object Association ......................................................................................................... 185
6.5 Object Context ......................................................................................................................... 196
6.5.1 Accessing Methods ......................................................................................................... 197
6.5.2 Data Object Context Switching ...................................................................................... 205
6.5.3 Interface Object Context Switching ............................................................................... 216
6.6 Collection Capabilities ........................................................................................................... 221
6.7 Basic Capabilities .................................................................................................................... 222
6.7.1 Data Retrieval/Extraction .............................................................................................. 222
6.7.2 Union and Looping ........................................................................................................ 224
6.7.3 Filtering ......................................................................................................................... 227
6.7.4 Sorting ............................................................................................................................ 230
6.7.5 Searching ....................................................................................................................... 232
6.7.6 Grouping & Aggregation ............................................................................................... 233
6.7.7 Performance Improvements – Using Walk Ex ............................................................... 245
6.7.8 Variables in Collection .................................................................................................. 247
6.7.9 Usage as Tables ............................................................................................................. 252
6.7.10 Dynamic Table Support using Unique Attribute .......................................................... 256
6.7.11 Collection Functions-Data Retrieval & Filtering ........................................................ 259
6.7.12 Voucher Object Structure ............................................................................................ 265

iii
Contents

Chapter 7: Action, Event Framework and Key Definition


7.1 Action Framework .................................................................................................................. 269
7.1.1 Understanding Actions .................................................................................................. 269
7.1.2 Invoking Predefined Actions .......................................................................................... 271
7.1.3 Invoking User Defined Actions ...................................................................................... 273
7.2 Action Association .................................................................................................................. 278
7.2.1 Action Association at Button/Key Definition ................................................................. 278
7.2.2 Action Association at Menu Definition .......................................................................... 279
7.2.3 Action Association at Field Definition .......................................................................... 280
7.2.4 Action Association at System Event Definition .............................................................. 285
7.2.5 Action Association for Object Specific Events ............................................................... 286
7.3 Classification of Predefined Actions ................................................................................... 289
7.4 Action Execution & Evaluation Process ............................................................................. 290
7.5 Scope of Actions ..................................................................................................................... 292
7.5.1 Limitations and Tips for Actions .................................................................................... 293
7.6 Dynamic Actions ..................................................................................................................... 296
7.7 Frequently used System and Object Specific Actions ...................................................... 299
7.7.1 System Actions ............................................................................................................... 299
7.8 Object Specific Actions .......................................................................................................... 309
7.8.1 Menu Actions – Menu Up, Menu Down, Menu Reject .................................................. 309
7.9 Key Definition ......................................................................................................................... 315
7.9.1 Attributes of the Definition Button / Key ....................................................................... 316
7.10 Event Frame Work ................................................................................................................ 322
7.10.1 Understanding TDL Events ......................................................................................... 322
7.10.2 Different Types of Events In TDL ................................................................................ 322
7.10.3 Object Specific Events ................................................................................................. 323
7.10.4 Event – Form Accept ................................................................................................... 324
7.10.5 Event – Focus .............................................................................................................. 324
7.10.6 Event – Before Print .................................................................................................... 325
7.10.7 Event – After Print ....................................................................................................... 325
7.10.8 Event – Start Import ..................................................................................................... 325
7.10.9 Event – Import Object .................................................................................................. 326
7.10.10 Event – End Import .................................................................................................... 326

Chapter 8: Object Manipulation and Storage in TDL


8.1 Object Manipulation & Storage An Introduction .............................................................. 331
8.1.1
Object Manipulation using the Tally Interface(Report & Menu) .................................. 332
8.1.2
Data Object Association – Report level ......................................................................... 333
8.1.3
Actions for Object Manipulation(Creation and Alteration) ......................................... 333
8.1.4
Action Modify Object in a Menu Definition .................................................................. 345
8.2 Object Manipulation using TDL/User Defined Functions (Procedural Capabilities) . 349
8.3 Object Manipulation using Data gathered from External Data Sources ........................ 350

iv
Contents

Chapter 9: TDL Procedural Capabilities


9.1 Introduction .............................................................................................................................. 353
9.2 Functions – In TDL ................................................................................................................. 353
9.2.1 In Built/Platform Defined Functions ............................................................................. 354
9.2.2 User Defined TDL Procedures/Functions ..................................................................... 354
9.3 Function – Building Blocks ................................................................................................... 358
9.3.1 Procedural Block ........................................................................................................... 363
9.4 Function Execution – Object Context .................................................................................. 363
9.4.1 Target Object Context .................................................................................................... 363
9.4.2 Parameter Evaluation Context ...................................................................................... 364
9.4.3 Return Value Evaluation ................................................................................................ 364
9.4.4 Programming Constructs ............................................................................................... 365
9.5 Actions ....................................................................................................................................... 383
9.5.1 System Actions ............................................................................................................... 384
9.5.2 Actions for Object and Context Manipulation ............................................................... 384
9.5.3 Actions for Variable Manipulation ................................................................................ 389
9.5.4 User Interface Actions ................................................................................................... 391
9.5.5 Debugging Actions ......................................................................................................... 393
9.5.6 File Input/Output Actions .............................................................................................. 399
9.5.7 File Input/Output Capability .......................................................................................... 400
9.5.8 Read/Write Operation on Text Files .............................................................................. 406
9.5.9 Reading a File ................................................................................................................ 408
9.5.10 Read/Write Operation on Excel Files .......................................................................... 409
9.5.11 Writing to a File ........................................................................................................... 410
9.5.12 Reading a File .............................................................................................................. 413

Chapter 10: Variable Framework


10.1 The Concept ........................................................................................................................... 421
10.1.1 Introduction .................................................................................................................. 421
10.1.2 Types of Variable ......................................................................................................... 421
10.2 Usage ....................................................................................................................................... 422
10.2.1 Variable Definition and Attributes ............................................................................... 422
10.2.2 Object Vs Compound Variable .................................................................................... 428
10.2.3 Variable Declaration & Scope ..................................................................................... 430
10.2.4 Using Modifiers with Variables ................................................................................... 440
10.2.5 List Variable Manipulations ........................................................................................ 442
10.2.6 Variable copy ............................................................................................................... 461
10.2.7 Copying from List Variable to List Variable ............................................................... 462
10.2.8 Compound List Variable as Data Source .................................................................... 491

Chapter 11: User Defined Fields, Validation and Controls


11.1 User Defined Fields .............................................................................................................. 495
11.1.1 UDF Definition ............................................................................................................ 496
11.1.2 Storing Values into a UDF .......................................................................................... 497
11.1.3 Retrieving values from a UDF ..................................................................................... 497
11.1.4 UDF Types ................................................................................................................... 498

v
Contents

11.2 Validation and Controls ....................................................................................................... 512


11.2.1 Field Level Attribute .................................................................................................... 512
11.2.2 Form Level Attribute .................................................................................................... 516
11.2.3 Menu Level Attribute ................................................................................................... 516
11.2.4 Report Level Attribute .................................................................................................. 517

Chapter 12: Advanced Reports and Printing


12.1 Advanced Reporting ............................................................................................................. 523
12.1.1 Tabular Reports ........................................................................................................... 523
12.1.2 Columnar Reports ........................................................................................................ 537
12.2 Printing .................................................................................................................................... 570
12.2.1 Modes of Printing / Printing Formats ......................................................................... 572
12.2.2 Report Printing / Printing Techniques ........................................................................ 572
12.2.3 Page breaks ................................................................................................................. 583
12.2.4 Multi Page/Part Printing ............................................................................................. 596
12.2.5 Printing on a Pre Printed Stationary ........................................................................... 600
12.2.6 Printing related Events – Before Print/After Print ...................................................... 601
12.2.7 Image Printing ............................................................................................................. 602
12.2.8 Additional Attributes and Functions ............................................................................ 605

Project Work: Inventory Management – Garment Store


1. F11 Features ............................................................................................................................. 615
2. Stock Item Master Creation ................................................................................................... 617
3. Voucher Type Master Alteration .......................................................................................... 621
a. Purchase Voucher Type Creation ...................................................................................... 621
b. Sales Voucher Type Creation ............................................................................................ 622
c. Implementation Logic ........................................................................................................ 622
4. Voucher Entry .......................................................................................................................... 623
a. Garment Purchase Voucher .............................................................................................. 623
b. Implementation Logic ........................................................................................................ 624
c. Garment Sales Voucher ..................................................................................................... 625
d. Implementation Logic ........................................................................................................ 625
5. Invoice ....................................................................................................................................... 626
a. Implementation Logic ........................................................................................................ 627
2. Garment Store Reports ........................................................................................................... 627
a. Stock Summary with Brand/Type/Colour/Size (Existing Report - Stock Summary) .......... 627
b. Instructions for Filtering ................................................................................................... 627
c. Implementation Logic ........................................................................................................ 627
d. Instructions for Filtering ................................................................................................... 628
e. Implementation Logic ........................................................................................................ 628
6. Columnar Reports ................................................................................................................... 629
a. Brandwise Itemwise Sizewise Sales (New Report) ............................................................. 629
b. Implementation Logic ......................................................................................................... 629
3. Color Scheme ........................................................................................................................... 630

vi
Contents

Use Cases
1. Use Case I – Import from Excel/Text .................................................................................. 633
2. Use Case II – Multiple Saved Configurations for Report ................................................. 642
3. Use Case III – Multiple Email Configurations ................................................................... 650
4. Use Case IV – Duplicating Vouchers .................................................................................. 656
5. Use Case V – Inter Company Data transfer ........................................................................ 660
6. Use Case VI – Multi Company Outstanding Report ......................................................... 665
7. Use Case VII – Voucher and Invoice Customization ........................................................ 669

vii
Chapter 1: Tally Technology – An
Overall Perspective

1.1 Introduction
We begin our discussion with the fundamental assumption that you are quite familiar with
Tally.ERP 9 as a complete business solution. Tally.ERP 9 is known for its sheer simplicity in
terms of user experience. The way business processes are handled, workflows are managed and
the complex reports are generated gives a clear indication on the usage flexibility and benefits
derived from the product by the business user. Before moving into the technology aspects of
Tally.ERP 9 let us have a cursory look into the major functional areas catered to by the applica-
tion.
Order to Payment (Purchase Process)
 Simple (Cash Purchase) to Advanced Purchase Processes (including Ordering,
Receipting, Rejections, Discounts, etc)
Order to Receipt (Sales Processes)
 Simple (Cash Sales) to Advanced Sales Processes (including Orders Received, Deliv-
ery, Invoicing, Rejections, Receipting)
POS Invoicing at retail
 Material to Material (Manufacturing Processes)
 Simple to Multi-Step material transformations
 Discrete and Process Industry cycles
 Handling Work in progress and valuations.
Payroll
 Simple to Complex Payrolls - including working with different units of measures
(e.g. job rates). Statutory compliances, their specification and their usage
MIS
 A complete set of reports for Financial, Inventory, MIS & Analysis
 Budgeting & Controls with advanced classification and filtering techniques
 Group Companies and multiple consolidation views
 Cross-Period Reporting, Forex handling, Bank Reconciliation

1
Tally Technology, An Overall Perspective

 One click Export option to port data into other applications (e.g. Spreadsheets) for
additional manipulation
Tax Audit using TallyNet
 TallyNet and its overall enabling environment for Remote Access Services
 Tax Audit Tools in Tally for the CA community to deliver affordable services to
addressing Security and Privacy concerns
Statutory Compliance
 Compliance Requirements and related configurations in Tally
 Implementation of Direct Taxes (TDS/TCS, FBT), Indirect Taxes (Excise, Service
Tax, VAT, CST)
1.2 Need for Tally Extensions
In addition to the default product capabilities, the user often requires additional modules in
order to suit the over expanding requirements of the business space. Sometime the requirement
may vary from a simple change like "having an additional field in the vouchers and dis-
playing the corresponding value in the invoice" to a complex requirement like "altering
the entire workflow from master entry upto the generation of MIS reports".
All these solution requirements can be catered to and deployed within minimal developmental
cycles using the RAD(Rapid Application Development) environment provided by Tally.
Have you ever wondered how a simple report is rendered on the Tally screen? Let us consider
the following simple steps to experience the development environment of Tally.
1. Open Notepad
2. Type the following on the screen and save it with a file name HelloTDL.txt

[#Menu: Gateway of Tally]


Add : Item: Hello TDL : H : Display: RepHello

[Report: RepHello]
Form : FrmHello

[Form: FrmHello]
Parts : PrtHello

[Part: PrtHello]
Lines : LneHello

2
Tally Technology, An Overall Perspective

[Line: LneHello]
Fields : FldHello

[Field: FldHello]
Set as : "Hello World"
3. Start Tally > Goto F12 > TDL Configuration
4. Click the button Local TDLs available on the right button bar
5. Specify the path of the file "Hello TDL.txt" within the List of TDLs to preload on
start up
6. Goto the menu Gateway of Tally menu and click on the menu item HelloTDL and
the following output screen appears:

Figure 1.1 Hello TDL Output

As a first time programmer on Tally platform, you might have experienced the following from
the above program execution.
1. The program is written in a language which is very different from a general purpose
procedural programming language
2. The program runs within the Tally Application
3. The language primarily contains certain syntaxes enclosed within square brackets

3
Tally Technology, An Overall Perspective

4. On user interaction with a particular menu item the main report is invoked as a sepa-
rate window
Each of the above observations can be elaborated to understand the crux of the Technology
behind Tally.
1.3 The Domain Specific Language – TDL
The entire application and the user interface via which the user interacts is completely built
using the Tally Definition Language. This is the Domain Specific Language of Tally which is
developed to provide the user with flexibility & power to extend the default capabilities of
Tally and integrate with external applications. TDL as a language provides capabilities for
Rapid Development, Rendering, Data Management and Integration.
1.3.1 Definition Language
TDL is a definition language. This provides the users with "named definitions" which allows
them to specify a set of properties/attributes for those definitions. Every definition should have
a name and it should be unique across the same definition type. Definitions are enclosed
within square brackets.
All the interface elements, data elements, style elements and procedural elements are created
using definitions. The order in which the specific attributes/properties come into effect is
purely based on user interaction. This is unlike a procedural language where the complete
sequence of execution is in the hands of the programmer.
1.3.2 Action Driven Language with Procedural Capabilities
TDL is a completely Action Driven language. Actions are triggered based on events which can
either be user or system driven. The specific segment of the code gets executed on the basis of
the Action performed. E.g. The programmer can write a code to create a Report, and the
action to trigger the report is specified with a menu item. The actual report comes into
existence only when the user selects the particular menu item.
The procedural elements are incorporated into the language where an Action can be created by
the programmer. This allows the specification of series of tasks/operations controlled by the
programmer. The fundamental aspects of conditional evaluation and looping are incorporated
which can be used for flow control, computation and object data manipulation.
1.3.3 Completely Object Oriented
TDL is a completely Object Oriented Language. Whether it an Interface, Data, Integration ,
Procedural or a styling element everything is an Object. There are mainly two types of Objects
in TDL Interface Objects and Data Objects. Interface Objects mainly determines the behavior
of the product in terms of user experience. Data objects suffice the information storage
requirements of the application. The data objects can either be used for temporary data display
and computation or can be persisted into the Tally Database.
Let us take an example of Interface Object. When a Report is created a unique report object is
instantiated. This report object in turn contains the various other objects used to build a report.

4
Tally Technology, An Overall Perspective

It emphasizes strongly on reusability. An object defined once can be reused and modified to
have additional properties of its own along with existing properties/attributes.
1.4 Tally – As a Development Platform
Tally is not only the application but is also a complete development environment which
enables the programmer to build extensions using Tally Definition Language in a RAD envi-
ronment.
1.4.1 Rapid Development
TDL is a rich language i.e it is possible to design a complex report or modify an existing report
by referring to a list of various components of the language. The components can be listed of
various types as
 Definitions, Attributes & Modifiers – Every definition has a permissible set of
attribute for defining specific behavior and usage
 Datatypes & Operators – A finite set of Datatypes and operators govern the type of
data and construction of valid expressions
 Predefined Actions & Functions – A comprehensive set of predefined Actions and
Functions available within the platform can be invoked/ called in order to perform
the desired task.
Moreover, the entire source code of Tally is provided along with the development suite. The
existing definitions can be used as templates and tweaked further to provide an extremely
rapid deployment environment.

We will introduce you to the development suite in the later sections of the
chapter.

1.4.2 Flexibility
TDL provides an amazing level of flexibility in the hands of the programmer. Most of the time
customer specific requirements may seem like majority of functional changes which are
required to be done but they may only be minor variation of the existing functionality which
may be done within no time. User can extend the default functionalities of the product by
writing only a few lines of code.

5
Tally Technology, An Overall Perspective

1.5 Components of a TDL program

Figure 1.2 Components of a TDL Program

The first TDL program "Hello TDL.txt" has been modified slightly in order to highlight the
various components of a TDL program. The code has been written using the development
suite Tally.Developer 9 where the various colors used for Syntax Coloring signify a specific
component of the TDL program. Refer to the legend box in the above figure to identify the
various components.
TDL comprises of many components such as definitions, actions, attributes, modifiers,
keywords, operators, functions and data types.
Definition – Definitions in TDL are the fundamental building blocks which control the
Interface Design and Data gathering requirements primarily. The procedural elements in the
language are also introduced in the language using definitions. In the above program all the
elements enclosed within square brackets are definitions. There are a predefined set of Defini-
tion Types available in TDL. The programmer can create multiple instances of each by
assigning a unique name to each.
Example:
Report, Form, Part etc. are definition types and the definitions names are prefixed with the
word “Hello”.

6
Tally Technology, An Overall Perspective

Attributes – The properties of definition are referred as 'Attributes'. Each definition has a set
of specific attributes. The attributes works on the concept of Name/Value value pair. Each
attributes has a Name and an assigned value.
Example:
Set As is an attribute of a field definition and "My formula" is the value assigned to it.
Actions – Actions are executors of the specified task with a definite result. This provides an
indication to the TDL interpreter (platform element), as to when a specific task has to be per-
formed. The definition Report and Menu are mostly originators of an action. These actions can
either be predefined or can be defined by the user by making use of the procedural elements.
Example:
The menu item Hello TDL invokes the Action Display
Operators – Like any other the programming languages TDL also supports all the standard
operators to construct an expression in addition to some TDL specific Operators. TDL
provides the following categories operators i.e. Unary, Arithmetic, String, Comparison/
Logical.
Functions -– The procedural flow is achieved in TDL with the help of functions. TDL has a
wide range of built-in functions for generic operations required by the end user. For specific
business requirements and data manipulations an user defined function can be written by
making use of the procedural elements.
Example:
$$LocaleString is a predefined function which takes the parameter as "My Test Field"
Data Types – The Data Types in TDL specifies the type of data which can be stored in the
field or to specify the type of the variable. In TDL there are two types of datatypes available
Simple and Compound.
Example:
String, Number etc are simple datatypes whereas Amount,Quantity etc are compound
datatypes
1.5.1 Underlying Tally Technology
The new Tally.ERP 9 has been designed in a way which provides extensive customisation &
solutioning capability which enables the developer community to exploit and deliver
solutions to complex business problems and requirements with the Power of Simplicity.
TDL – Tally Definition Language takes care of all aspects of solution development ie form/
screen design, entries, generating reports, data export, printing and mailing. TDL provides tre-
mendous capability in the hands of the programmer to extend, customize and build solutions
on Tally.ERP 9.
Moreover the language itself is designed keeping the Business/Application programmers in
mind. Programmers with sound domain experience can concentrate on the implementation of
business requirements rather than being bogged on by technical nuance of the platform. The

7
Tally Technology, An Overall Perspective

Programmers can be up and developing solutions on Tally.ERP 9 development platform in few


days.
Tally.ERP 9 has a completely reliable, extremely robust and self managed underlying data
management system which requires zero maintenance thereby dramatically lowering total cost
of ownership. This addresses a key problem most business face, more so small business -
availability of technical expertise required to manage IT systems.
Let us analyze the Tally Architecture to understand the technology behind Tally.
1.6 Tally Architecture – Overview

Figure 1.3 Tally Architecture

8
Tally Technology, An Overall Perspective

The entire Tally architecture can be conceptualized as being divided into three layers
 The Application / Tally.ERP 9 Layer
 The TDL Language and Interpreter Layer
 The Platform Layer / Engine
1.6.1 The Application/Tally Layer
Application layer forms the topmost layer of the product architecture. All the user interactions
take place at this layer. It is through this interface that the user exploits complete functionali-
ties offered to them. The product exploits the capabilities of the Operating System using the
intermediate layers between the application and the OS.
1.6.2 The TDL Language and Interpreter Layer
The heart of Tally, this layer forms the key link between the application and the platform layer
consisting of
 Tally Definition Language
 TDL Interpreter
Tally Definition Language is developed to provide the user with flexibility and power to
extend the default capabilities of Tally and integrate with external applications. TDL provides
a development platform for the user. The entire User Interface of Tally is built using TDL.TDL
as a language provides capabilities for Rapid Development, Rendering, Data Management and
Integration.
TDL works in an interpreted environment. In TDL, definitions are deployed by use and not by
mere existence. An action performed by user will trigger a particular segment of code to get
executed. The interpreter examines each line and throws an error when encountered.
1.6.3 Platform Layer
The capabilities which TDL offers are due to the strong platform capabilities of Tally. This is
the lowermost layer of Tally which interacts with the OS and ultimately the file system. The
various components of the platform layer are
 DB Engine
 ODBC Engine/Driver
 Language Parser
 Output/Rendering Engine
 Function Library
 User Interface/ Business Logic
 Memory Management

All the retrieval and manipulation requests to the database by the application program are
handled by the Database Engine. Tally database is a true OODBMS (Object Oriented

9
Tally Technology, An Overall Perspective

Database Management System). It is possible to store data as objects and retrieve data as
objects. In other traditional OODBMS, data pertaining to an object is internally converted into
disparate files and stored, but in Tally database data for an object is stored as it is as a block.
This allows faster retrieval of data. Object Oriented Recursive Management System follows
the concept of Flexi-Length Record, Flexi-Field, Self-Indexed weighted file structure for a
extremely compact and fast database. Fault tolerance is built in the system i.e., it uses the
CRC(Cyclic Redundancy Check) mechanism to achieve this. Transaction support is provided
by using roll forward capability i.e. it is extremely robust in case of power failure. It provides
concurrent access in a multi-user environment.
Tally File System consists of Data files (Master, Transaction, Link Masters), Msgfiles (Trans-
action Management) and State Files (concurrency control and exclusivity control).
It follows the concept of Embedded and Weighted Indexes. In other traditional databases,
separate index file is maintained. In Tally, indexes are built into the data files. This facilitates
faster retrieval of data.
ODBC Engine/Driver handles the ODBC calls from external applications to Tally Database
or from Tally to external Data Bases using SQL (Structured query language). Tally can act as a
client accessing data from external databases and as Server it allows the data access from Tally
to external Applications.
TDL works in an interpreted environment. The Language Parser consisting of Syntax and
Formula parser enables the parsing of syntax and semantics of the statements and expression
parsing. Whenever an statement containing a formula is encountered by the interpreter the
formula identifies the type of the formula i.e. Method, Function, Expression Formula, etc.
which is determined by the type of symbol prefix i.e. $, $$, @, etc.
Managing multiple outputs types from Tally and rendering it based on the output environment
is the capability of the Output Engine. TDL has the capability to output to Screen, Printer,
File (XML, SDF), Mail, and HTTP using this engine. If we talk specifically about Display,
Tally has a unique capability to accommodate the entire contents into the screen. It also
shrinks the data to fit within the specified width of the field. The mechanism using which data
is made to fit the screen is taken care by the Screen Management algorithm. Scrolling, Page
Break, etc. is provided as functionalities.
Some capabilities which are required by the application based on business type it caters to are
built in into the system as business logic. The Business Logic/UI engine takes care of valida-
tion techniques and checking of business rules. If the capabilities and validations were to be
provided in the TDL layer, it would consume a large amount of time for processing. Bundling
this at the platform layer enables an increase in application speed and ensures integrity of data.
For e.g., Some validation mechanisms like matching the Debit Credit totals can never be
bypassed even if data is pushed from an external application to Tally.
Function Library provides a wide range of functions for performing various activities. These
functions execute by accepting a predefined set of parameters returning a value to the calling
expression from the TDL layer.

10
Tally Technology, An Overall Perspective

All the memory requirements of the application when it is running are taken care of by
Memory Management component. This takes care of interactions with the Operating System
on the memory requirements of the application. This will take care of allocating a chunk of
memory from the OS and managing it. From time to time, the common activities such as
garbage collection, compacting and releasing the unused memory aids in optimal use of
computer memory.
All of these platform components are developed in a language which can interact with the
Operating System directly. These internally make use of various algorithms, OS calls (System
calls) and Data Structures for the interactions. The platform developers interact at this layer
and provide new functions and TDL language capabilities to be used by the programmers.
1.7 Tally Technology – Capabilities
1.7.1 Solution-ability & Customizability
TDL is a powerful tool in the hands of the programmer which enables Customizability &
Solutioning capability in the product. TDL is platform independent, i.e., the TDL programs
remain the same irrespective of which Operating System/ Network Environment one uses
TDL automatically takes care of all developmental features of a solution, be it entries, reports,
printing, data export in various formats with a single unified program. There is no requirement
of resources with varied technical expertise to build these diverse functionalities unlike other
technologies which may require a Database programmer, an Application programmer, a
systems programmer, etc.
1.7.2 Multiple Output Capability
Same language can be used to output to multiple output devices and formats. Whenever an
output is generated this can be displayed on the screen, printed ,transferred to a file in particu-
lar format, mailed or transferred to a webpage using Http protocol.
1.7.3 Data Management Capability
As we have discussed earlier data is stored and retrieved as objects. There are a few internal
objects predefined by the platform. Using TDL it is possible to create and manipulate these
information with ease. If an additional field is required by the user to store information as a
part of the predefined object that capability is also provided ie by using TDL the user can
create a new field and store value into the same which can be persisted in tally database.
1.7.4 Integrate-ability
Tally has been designed in a way which provides extensive integration capability which
enables the developer community to exploit and deliver cross platform solutions thereby
allowing seamless interoperability among multiple applications with the Power of Simplicity.
Tally.ERP 9 is endowed with limitless possibilities due to its capability to interface with other
applications, devices and the internet. Tally.ERP 9 allows export and import of data in various
formats like CSV, Excel and so on.

11
Tally Technology, An Overall Perspective

It can act as a backend(server) for various web-applications built on platforms like ASP, PHP
etc or other applications accessing data using ODBC. Using TDL data can be accessed from
any external ODBC Database. TDLs procedural capabilities perform various tasks including
batch jobs, scheduled events and so on. It can also be made a part of a larger system process.
Tally provides different API's (Application Programming Interfaces) to integrate data.
 XML
 ODBC
 DLL
These allow seamless integration between application/database in two modes:
Online Mode
 Tally to Tally using Synchronization
 Tally to External Application and vice versa using the Interfaces Available
 Tally to Web Service using HTTP Interface
Offline Mode
 Tally to External Applications using Export
 Data from External Application in XML using Import

In this book we will not be concentrating on the Integrate-ability of Tally. The


document “Tally.ERP9 – Integration Capabilities” available in the CD
explains the integration aspect of Tally.

1.8 Tally Development Environment


We will now focus on the technology support provided for Solution-ability and Integrate-
ability of Tally.ERP 9.The entire set of services is available in the form of what we call it as
Tally Development Environment( TDE). The environment comprises of
 Tally Definition Language(TDL) integrated with Tally.ERP 9 Platform
 The Tally Development Suite productized as Tally.Developer 9 (TD 9)
 Set of Tools - Integrated with the Development Suite
 Associated Support – For TDL and TD 9

We have Tally Definition Language (TDL) which is a domain specific development language
of Tally and is integrated with Tally. ERP 9 platform. It enables the programmer to develop
solutions IN and Around Tally. We have comprehensively covered the capabilities of Tally

12
Tally Technology, An Overall Perspective

Technology and TDL in the preceding sections of the chapter. It is a powerful instrument in
the hands of the TDL programmer to extract maximum benefits from Tally!!!
Tally.Developer 9 is a comprehensive development suit designed specifically for program-
ming in TDL (Tally Definition Language). Tally.Developer 9 comes with its unique features
in terms of :
 Easy programming by Syntax Colouring, Tagging and Navigation of code, Auto
Completion, Project Management and so on
 Ease of debugging with error listing and diagnosis
 Build , Compilation / Validation / Execution of Code from within the product
 Authorization techniques for TCP(Tally Compliant product) ensuring IP protection,
control license usage and minimize revenue leakage.
 Easy Distribution mechanism using licensing and subscription renewals
 Easy customer serial management
 Access to the Complete Tally source code as a reference
 Ability to load multiple versions of the source code
 Instant references to TDL Language API's such as Schema, Definition and
Attributes, Functions, Actions and so on
 Ability to extend multilingual support to the product, customization, modules in
localized languages with the powerful dictionary manager tool
 Rich set of TDL language documentation and programming samples
 Access to the support centre / KB
 Tools that help to develop and test external application's integration with tally (Tally
connector)

The products Tally.ERP 9 and Tally.Developer 9 can be downloaded from our


website www.tallysolutions.com from the download section. Also refer to the
technology related information and updates from the section "Developer
Network" on the home page

1.8.1 Getting Started with TD 9


Before we start writing a first TDL program using Tally.Developer 9, it is important to get
familiar with the working environment.

13
Tally Technology, An Overall Perspective

In order to be able to enjoy all the features and functionalities of Tally.Developer 9, it is


important to use the License version with valid paid subscription. We also have the evaluation
version available.

Please refer to the "Getting Started with Tally.Developer 9" for the detailed
explanation of Installation and Licensing process. The document can be down-
loaded from the Tally website.

After launching Tally.Developer9, the first screen is displayed as follows:

Figure 1.4 TD9 First Screen

The developer window is divided in four sub windows namely Browser Window, Editor
Window, Property Window and Output Window.
1.8.2 Usage of Different Explorer Windows
Browser window consists of four tabs: Project, Definition, Schema and Function. By default
the Project tab (Project Window) is active which displays all the loaded projects in a tree view.

14
Tally Technology, An Overall Perspective

Editor Window is the place which displays the actual file content. Output window also
contains four tabs, Output, Build, Search and Command. Property windows display additional
information for the item selected in the Browser window.

Please refer to the Tally.Developer 9 Help file for the detailed explanation of
each window and their functionality.

1.8.3 Usage of different Browsers and Property Window


The Browser Window and Property Window are used together to provide instant information
about the selected item in the Window. As mentioned earlier, the Browser window is contains
four tabs, one each for Project Browser, Definition Browser, Schema Browser and Function
Browser.

Project browser displays the loaded projects and the folder and files in each in tree view.
When a Project is selected the property window displays the project statistics like Project
location, number of files in the project, project GUID etc.

Definition browser displays all the definition types in TDL and the list of all the attributes
supported by each definition as a tree view. The property window displays a brief description
of the selected definition type and addition information like number of attributes, category etc.
If the attribute is selected than the property windows displays details like attribute type,
number of parameters, and even for the sub attribute.

Schema browser displays the metadata for all the objects of Tally database as a tree view. The
object structure displays list of all the methods and collections available in each object of Tally
schema. The Property window displays details corresponding to the object , collection or the
method name selected. If a method name is selected then the displayed details are the data type
accepted by that method and whether it is a repeated or not.

Function browser displays list of all the built-in functions in TDL. The functions are listed
under the specific category. The Property window displays details like Total number of param-
eters, mandatory parameters, category, execution mode and return type along with the details
of each parameter like parameter type, data type and mandatory flag.

Action browser displays list of all the actions in TDL. The actions can be viewed alphabeti-
cally, category wise or definition wise. The Property window displays details like Total

15
Tally Technology, An Overall Perspective

number of parameters, mandatory parameters, category, execution mode and return type along
with the details of each parameter like parameter type, data type and mandatory flag.

Please refer to the "Getting Started with Tally.Developer9" for the detailed
explanation of Installation and Licensing process. The document can be down-
loaded from the Tally website.

1.8.4 Coding Convention


In any language the communication standards should be followed for better understanding. In
a programming language also some coding conventions are used. These are not hard and fast
rules, instead these are guidelines that improve the readability of the program. The programs
written as per coding convention are easy to debug and update.
The conventions followed while writing the TDL code are as follows:
1. Give meaningful names to the definition and use Title Case for naming.
2. After each Definition one line space should be given.
3. Align the first colon among all attribute within a definition
4. All the Definitions should be indented to the right except the Report, Form and Initial
Parts within the Form
5. Appropriate Case must be maintained
6. Assign Meaningful Names to Definitions, UDFs, Variables and Formulae
7. Insert proper comments, as and when necessary
In TDL Procedural/Function Definition, coding standards are as follows:
1. In the Declaration Section, the order is as shown:
Parameters

Static Variables

Variables

List Variables

Local Formulae

2. Label must be incremental i.e. 00, 10, etc…


3. Action names\ Programming constructs must be in ALL caps
4. Proper Indentation inside each procedural block.
The coding convention when followed results in better readability
1.8.5 Navigating and understanding the Tally Source Code(Default TDL project)
Whenever Tally.Developer 9 is launched it loads the project Default TDL. The project Default
TDL contains the source code of Tally.ERP 9. The application user can search and navigate
the source code and then based on the user requirement modify the functionality.

16
Tally Technology, An Overall Perspective

1.8.6 Folder Structure and File naming convention


The project Default TDL is easy to navigate as the files are arranged in Folders and follow a
proper naming convention. The files are categorized based on the functionality that they
provide. For example all the files containing menu definitions are in folder Menus, all the
company related files are in Company folder and so on.
1.8.7 Navigating and Searching project Default TDL
Navigating the Default TDL project is very easy and simple since the files related to function-
ality are grouped together in one folder and follow proper Naming Convention as explained
easier. Apart from this Tally.Developer 9 provides many options such as, Find In Files, Defini-
tion Reference, Attribute Reference, Jump To etc.
Direct navigation is also provided as Hyperlink. The user can press Ctrl + mouse click on the
Definition name to view the detailed description of selected definition.
1.9 TDL Program Life Cycle
A typical TDL program Life Cycle from development till deployment can be specified as
follows. Try out these steps with the "Hello TDL" program given at the beginning of the
chapter.
Step I:Coding and Creating a Project – Writing the TDL program in a the editor window
provided within Tally.Developer 9
A program can be written using the editor window provided within the TD 9 interface. The
Source file will always be saved with an extension .txt/.tdl. In order to deploy the TDL this
needs to be converted to TCP file and can be secured to work with only specified Tally serials.
In order to do the same we need to create a Project File with an extension .tpj and add the
source files to it. While creating the Project itself the various options for authorization of the
tcp will be set. These will apply when we finally build the TCP.

17
Tally Technology, An Overall Perspective

We have an option while creating Project to add an Existing Source File or a New File which
will be created subsequently.

Figure 1.5 TD 9 - New Project Window

18
Tally Technology, An Overall Perspective

The authorization details like the Author Name, Serial Numbers, Product GUID its can be
specified in project Properties Build Options tab.

Figure 1.6 TD 9 - Project Properties Window

Step II:Compilation & Error diagnosis – Checking the program for possible syntax and
other errors by compiling the program
This can be either a single step where we can compile the project directly (which will list the
syntax errors and other errors in the program) or a two step process where we can check for
syntax errors first and then compile the program.
Checking Syntax Errors
The application Tally.Developer 9 comes with a built-in compiler which helps in finding out
the syntactical errors before attaching the TDL to Tally.ERP 9. The user can select option List
Syntax Errors or simply select compile.

19
Tally Technology, An Overall Perspective

Compiling Project
Compiling project provides the user a flexibility to compile all the files in a project in one go.
The user can click on the error message displayed in the output window to navigate to the
location in file which has an error.
Step III:Build TCP(Tally Compliant Product) – Securing the code by creating a TCP
The step to create a TCP file is referred as building in the Tally.Developer 9. The user can
select the Build option from Build Menu.The (.tcp) file corresponding to the .tpj file is created
using the various authorization settings configured while creating the .tpj.
Step IV:Deploying the TCP – Associating and executing the tdl program (tdl/txt/tcp) with
Tally.ERP 9. The TCP/TXT can be associated and executed within Tally.ERP9 in two ways.
 Specifying TDL file in Tally.ini
 Specifying TDL file in Tally.ERP 9 configuration screen
Specifying TDL files in Tally.ini
The path must be specified in the Tally.ini file using the parameter called 'TDL'. In the initiali-
zation file two parameter values must be specified. The value of parameter User TDL must be
set to Yes and the value of parameter TDL is the TDL file path. If the parameter 'User TDL' is
set to No, Tally.ERP 9 will not read any TDL parameters specified in Tally.ini file.
To associate the MyFirstTDL.tcp file with tally.ERP9, specify the following in the Tally.ini
file:
User TDL = Yes
TDL= C:\MyFirstTDL.tcp
Now save the file and launch the Tally.ERP 9 application.
Specifying TDL file in Tally.ERP 9 configuration screen
Alternatively, the TDL file name can be specified in the configuration screen displayed by
selecting menu item 'TDL Configuration' from the F12: Configure menu. In this screen, click
on the button Local TDLs which displays the TDL Configuration screen. Specify the value
Yes in field 'Load TDLs on Start up' and the <Path\filename> with extension in 'List of TDLs
to preload on Tally Startup' field respectively.
Enter the path of HelloTDL.tcp as shown:

Figure 1.7 TDL Configuration Screen

20
Tally Technology, An Overall Perspective

Now in the main menu Gateway of Tally a new menu item My First TDL will appear. Select
the menu to see the result as shown:

Figure 1.8 Output of My First TDL program

Source Code Protection


As explained earlier, a tdl file can be secured by providing the authorization details in the
project properties and then creating a TCP. The TCP can be protected to run for specific Tally
Serial Nos only. This process is referred as Build.
At a later date, the customer using the TCP may require some enhancements. The developer
has the option to retrieve back the source code from the TCP.This process is known as Decom-
pilation. The original folder structure and files along with the .tpj file is retrieved after decom-
pilation.
The Decompilation is available as a service on the Web Control Center. This facility is
available only for valid Silver/Gold subscription users. Users with free evaluation serials are
not authorized for using this service. This service allows the user to decompile one TCP at a
time. The decompiled file is available as Zip file which can be downloaded and saved on the
user system.

21
Chapter 2 : Definitions, Attributes
and Modifiers

Introduction
An overall insight on the Tally Technology, the Development language and the Tool has given
us a strong foundation over which we can proceed and explore the various domains of Tally
Definition Language.
As we know, TDL is a definition language. This provides the users with named definitions
which allows them to specify a set of properties/attributes for those definitions. Every defini-
tion should have a name and that it should be unique. Definitions are enclosed within square
brackets.
All the interface elements, data elements, style elements and procedural elements are created
using definitions. The order in which the specific attributes/properties come into effect is
purely based on user interaction. This is unlike a procedural language where the complete
sequence of execution is in the hands of the programmer.
The properties of definitions are referred as attributes. Attributes decide behaviour of the defi-
nitions. We have a set of modifiers which allow the programmer to alter either the definitions or
the corresponding Attributes.
This chapter will help us to cover the concept of definitions, its categorization and then
progress on to discussion for attributes, its types and modifiers.
2.1 Definitions
A definition is identified by its type and unique name. TDL is definition language based on
object oriented programming concepts which strongly emphasizes on reusability. Once a defi-
nition is created it can be reused any no of times. Not only can it be reused but new features can
be added along with existing ones.
A definition is created as per below:
Syntax
[<Definition Type> : <Definition Name>]
All definitions start with an open square bracket and ends with a closed bracket.

23
Definitions, Attributes & Modifiers

Where,
<Definition type> is name of predefined definition types available in the language e.g. Col-
lection, Menu, Form, Part, Line, Report etc.
<Definition Name> is any user defined name which the user provides to instantiate the defini-
tion i.e. whenever a definition is created a new object of a particular definition type comes into
existence.
Example:
[Part: PartOne]
In the example the type of definition is part and the name of definition is PartOne. The combi-
nation of definition type and definition name must be unique. There are 20 definition types in
TDL.
Proper naming conventions allow us to ensure uniqueness and better code readability/clarity
across projects.
Naming Conventions for Definitions
 Definition name must be unique for a particular Definition type
 Definition names are case and space insensitive
 Special characters are not allowed
 Definition names should not start with numerals
 The reserved words cannot be used as a Definition Name
 The Definition names that have been used by default TDL cannot be given as a Def-
inition name by User defined TDL. If required, the default definitions can be reused
/modified
 It is strongly recommended that Definition names be meaningful and indicate the
functionality of the element being defined. For example, prefix MBS to indicate My
Balance Sheet for all Definition used in a TDL program to create Balance Sheet
report
2.1.1 Definition Categorization
There are twenty definitions in TDL which can be categorized based on their functionality and
usage. Some definitions are used to design the Interfaces and control the Presentation Layers.
Few suffice the fundamental requirements of data gathering and processing requirements. The
procedural capabilities included in the language are also provided using definitions.
The broad categorization is given as below
 Interface Definitions
 Data Definitions
 Formatting Definitions
 Integration Definitions
 Action Definitions

24
Definitions, Attributes & Modifiers

 System Definitions
 Procedural Definitions

Figure 2.1 Definition Categorization

Interface Definitions
These definitions control the construction of the Interfaces. Mostly oriented at the presentation
layers of the application. The various visible elements on the Tally screen are Menu, Report,
Button and Tables fall under the category of Interface Definitions. The fundamental interface
definition is the “Report”. In order to create a Report, the other sub elements will be required
which have a predefined containership and cannot exist on their own.

25
Definitions, Attributes & Modifiers

Definitions in this category include


 Menu – A menu displays a list of options. Based on the menu item selected by the
user the the action to be performed is determined. The first menu which appears on
the screen when Tally starts is the ‘Gateway of Tally’. A Menu can activate another
Menu/Report/call a function.
 Report – All the screens in Tally whether an input screen or an output screen, it is
created using the Report definition. It requires sub elements Form, Part, Line, Field
to define its appearance. A Report contains one or more Forms
 Form – This is the area which is used to display the contents of a report. A Form
contains one or more Parts
 Part – The form area can be further divided to small sections known as Parts. Part
consists of one or more Lines. Part can contain sub parts which in turn contain one or
more lines
 Line – A line consists of one or more fields. The line specifies the order in which
the fields are displayed on screen
 Field – A field is place where the data is actually displayed or entered. The data can
be a constant or variable data. A field can also contain sub fields
 Button – User can perform an Action in three ways i.e. by selecting a menu item, by
pressing a key and by clicking on a button. Button definition allows the user to dis-
play a button on the Button bar and execute an action on invocation
 Table – Table is an alias of definition type Collection. It displays a list of values as
Tables. Data from any collection can be displayed as a Table

The definitions Menu and Button falls under the category of Action and
Interface definition both as they control the appearance and perform an Action
as well

Example:
In the example a menu definition is created with the name My Menu. It contains two items
Item A and Item B. Item A invokes the report Rep A which is constructed using the various
interface definitions as per hierarchy shown in the picture.

[Menu: My Menu]
Add: Item : Item A: Display:Rep A
Add: Item : Item B: Display:Rep B

26
Definitions, Attributes & Modifiers

[Report : Rep A]

[Form :Form A]

[Part:Part A]

[Line:Line A]

[Field:Field A]
Data Definitions
The Definitions which suffice the data gathering, processing, storage and manipulation
requirements are termed as Data Definitions.
Definitions in this category include
 Object – As we know TDL is an Object Oriented Language. Whenever we create a
new Interface Definition an object is instantiated. Under the Data Definition Cate-
gory we are referring to Objects which contain Data and methods to manipulate its
own data. The Data Objects can further be categorized into Internal (predefined) and
TDL Objects(user defined).TDL follows a hierarchical data structure ie an Object
can further contain a single or multiple sub objects. The various interface elements
either pull/push data from/into the data objects. A Ledger / Group is an example of
an internal Object.
 Collection – The fundamental Data gathering and processing element of TDL is the
Collection definition. The bulk of aggregation, chaining and Integration capabilities
are delivered using Collections. A collection is a group Object/Collections. The
source of Objects in the collection can be either an Internal/TDL Object.

The definition Collection falls under the category of Data and Integration defi-
nition as it provides Data Processing and Integration Capabilities as well.

 Variables – Variables in TDL (Tally Definition Language) are light weight/context


free structures which can hold values during the execution of a program. The values
of these variables are initialized when it is created and can change during the entire
execution of program. It is also possible to perform the various manipulation opera-
tions like insert/update/delete/sort and find on a variable.

27
Definitions, Attributes & Modifiers

Example:1
In the example a collection definition My Coll is created which has two objects O1 and O2.
The Object O1 is created using the definition Object with name O1.
[Collection :My Coll]
Objects :O1, O2

[Object:O1]
Name :”ABC”
Example:2
The collection definition “LedColl” is created using the internal ledger objects.
[Collection :LedColl]
Type:Ledger

Formatting Definitions
We have earlier covered the construction elements of the Interfaces. These definitions control
the appearance of the content or elements on the screen.
Definitions in this category include
 Style – Style determines the appearance of the text to be displayed by using a partic-
ular font scheme. Font name, Font style and font size can be changed/defined using
style definition. In default TDL the pre-defined Style definitions are Normal Bold,
Normal Italic, and Normal Bold Italic. We can create our own style definitions and
apply them as required
 Border – This definition is used to create borders of a specific type. Thin Box, Thin
Line, Common Border are all examples of pre defined borders which can be applied
to Part, Line and Field definitions
 Color – Color definition is used to define a color. A name can be given to an RGB
value of color. Once a name is assigned to an RGB color value it can be referred in
the color attribute of the field.

Example:
In the example a Color definition New Blue and a Style definition New Style is created and
applied to the contents of the Field My Field.

[Color :New Blue]


RGB : 102,105,235

28
Definitions, Attributes & Modifiers

[Style :New Style]


Font :”Arial”

[Field :My Field]


Set As : “Hello World”
Style : New Style
Color : New Blue

Integration Definitions
The definitions which facilitate the integration of Data from external applications to Tally
form a part of Integration Definitions. Import of Data using standard API’s ODBC,XML and
DLL is provided using the Collection Definition. Though XML is the de facto standard for
information interchange in recent times, still there may be a few applications which support
SDF/Fixed Width format for storing the data.We have the definitions ImportFile and Import
Object which enable integration with this format.
Definitions in this category include:
 Collection – The collection definition which is primarily a Data Definition falls
under this category this provides the capability to import data from a variety of dis-
crete External Data Sources. The data objects gathered through the API’s ODBC,
XML and DLL can be further persisted into the Tally DataBase.
 Import File – Import file allows describing the structure of each record in the ASCII
file that is being imported. The field names and the width is specified as the
attributes of this definition.
 Import Object – Import Object specifies the Internal Object into which the data
being imported is stored. It also defines the mapping of the Object being imported to
the corresponding Internal Object.

Example:1
In the example a collection is created using the data gathered from an XML located at an
HTTP URL.
[Collection :HTTPColl]
Remote URL : “http:\\localhost\MyFile.xml”: ASCII
Example:2
In the example an Import File definition I45Mast is created to define the structure of the
external file being imported and the data is imported into the corresponding Ledger object as
defined using the Import Object definition I45Ledger.

29
Definitions, Attributes & Modifiers

[Import File : I45Mast]


Field : I45Name : 30
Field : I45Parent : 30
Object : I45Ledger

[Import Object :I45Ledger]


Type :Ledger
Storage :Name : #I45Name
Storage :Parent : #I45Parent
Action Definitions
The definitions which allow triggering of an Action are categorized under Action Definitions.
These Actions may operate upon a particular Definition.
Definitions in this category include
 Key – This is the fundamental definition which allows us to to associate an action
with the key combination. The action is performed when the associated key combi-
nation is pressed.
 Button – Along with the Interface aspects the prime function of the button defini-
tion is also to associate an action on pressing the same. We have an option to provide
a key combination performing the same function.
 Menu – The definition adds menu items to the Menu which is displayed on the
screen and in turn is used to trigger Actions associated with them.
 Function – A function definition can also trigger an Action. It is possible to trigger
a sequence of Actions from within a Function
Example:1
In the example a key definition “My Key” is created which is used to trigger an action Display
on pressing “Ctrl+K”
[Key : My Key]
Key :Ctrl+K
Action :Display: Rep A
Example:2
In the example the menu definition My Menu is created which has a menu item Item A to
trigger the action Display.
[Menu : My Menu]
Add: Item : Item A: Display: Rep A

30
Definitions, Attributes & Modifiers

System Definitions
System definitions are viewed as being created by the administrator profile. Any items defined
under system definitions are available globally across the application. It is not possible to
instantiate a new Object of type System unlike other definitions given above. System defini-
tions can be defined multiple times in TDL. The items defined are appended to the existing
list.
Definitions in this category include:
 System: Form Keys – The key names that are defined under Form Keys will be
available by default to all the form definitions.
 System: Formulae/Formulas – The formulas which are included in the list if Sys-
tem Formulae/Formulas can be shared by all the TDLs. These are referred as Global
Formulae.
 System: Menu Keys – The key names included in the list of Menu Keys will be
available to all the Menu definitions by default.
 System : TDL Names – In this definition, the frequently used business keywords
can be stored as system names. System names are keywords which have an identifier
associated to it. Only once the value will be saved.
 System : UDF – The additional storage required as per the business requirements
are created using the definition System : UDF
 System : Variable – If the variables are to be declared at the System scope the same
is done using this definition. The variable thus declared will be available across all
reports in Tally.
 System : Events – This definition is used to define certain events and associate the
corresponding actions based on the occurrence of the same.
Example:1
In the example below a variable My Variable is defined at the system scope.
[System: Variable]
My Variable : “Value“
Example:2
In the example below an action Display is triggered on the occurrence of the System Event
Load Company.
[System :Events]
CmpLoadEvent3: Load Company :TRUE:Action:Display:"Balance Sheet"
Procedural Definition
Definition in this category include:
 Function – It has been possible to include the procedural capabilities in the language
using the definition Function. Prior to Tally.ERP 9, the tasks to be triggered from the

31
Definitions, Attributes & Modifiers

key/button/menu item used to be only those Actions which were provided by the lan-
guage/platform. Using the function definition the programmer can now define his
own set of tasks to be performed and the same can be triggered from a key/button/
menu item. Also, it can be used to perform computations and can be called from
within an expression. This can be used in an evaluation or for execution.
Example:
A function definition SI Calc used to calculate the Simple Interest and return the result to the
calling program.
[Function: SI Calc]
Parameter: P : Amount
Parameter: R : Number
Parameter: T : Number
Returns : Amount
Variable : Interest: Amount

01 : SET : Interest: (##P * ##R * ##T) / 100


02 : RETURN : ##Interest

2.2 Attributes
Each definition has properties referred to as Attributes. There is a predefined set of attributes
provided by the platform for each definition type. The attribute specifies the behavior of a def-
inition. Attributes differ from definition to definition. A definition can have multiple attributes
associated with it. Each attribute has a 'Name' (predefined) and an assigned value (provided
by the programmer). The values to be set for an attribute can either be a constant or the result
of an expression evaluation. The expression may be a combination of methods, variables,
formula etc which may be evaluated based on a condition.
Syntax
[<Definition Type> : <Definition Name>]
<Attribute Name> : <Attribute Value>
Where,
<Attribute Name> is name of the attribute specific for the definition type
<Attribute Value> can be a constant or a formula

Example:1
[Part: PartOne]
Line : PartOne

32
Definitions, Attributes & Modifiers

Example:2
[Form: Form One]
Part: Part One
An attribute can have more than one value separated by “:”. When an attribute accepts more
than one value, each sub-value is referred as sub-attribute. The number of sub-attribute allows
to classify the attribute as either Single, Dual, Triple.
Syntax
<Attribute Name> : <Sub-Attribute> : <Sub-Attribute>
Where,
<Attribute Name> which is a keyword is called as the primary attributes.
<Sub-attribute> doesn’t have a keyword associated with it. Primary attributes are recognized
based on the keyword.
<Sub-attributes> are recognized based on the pre-defined internal order. If the order is
changed the specified action will not take place. <Sub-Attribute> can be optional.

Example:
Explode : <part name> : <condition>
Here Explode is a primary attribute and <part name> and <condition> are sub-attributes.In
the order of <part name> and <condition> is changed, the code will not execute the explode
action.
In this example sub-attribute <part name> is mandatory while the sub-attribute <condition>
is optional. Sub-attribute finally evaluates to a value which is of a particular data type.

2.2.1 List Type Attribute


There are certain set of attributes which accepts only Single values whereas some attributes
can accept multiple values. The values to be specified can be provided either as comma
separated or by repeating the same attribute with n values n no of times (where n can be any
number).
In the example below the Part PartOne contains two lines LineOne and LineTwo.This can be
specified by providing the line names as attribute values for the attribute Line.
[Part: PartOne]
Line : LineOne, LineTwo
;; Here LineOne and LineTwo are separated by comma

[Part: PartOne]
Line : LineOne

33
Definitions, Attributes & Modifiers

Line : LineTwo
;; Observe the multiple occurance of the attribute Line with values LineOne and LineTwo respectively

This type is in contrast with the attributes which accept ONLY one value where these values
can fall into the category of Single/Dual/Triple. Whenever multiple values are provided to
such attributes the recent value overwrites the previous value.
In the example below we have provided two values to the “Set As” attribute
[Field : FieldOne]
Set As :”Value One”
Set As :”New Value”
;; Here FieldOne displays the “New Value” as Set As accepts only one value the the “New Value” overwrites the
previous value “Value One”

2.2.2 Attribute Feature – Discreteness


Discreteness is the property of an attribute. This property is applicable to all the categories of
list type attributes. Whenever we say that an attribute can assume multiple values i.e. an
attribute is list type, the values which it takes has to be discrete and unique. Discreteness is a
behavior where an attribute cannot have same value repeated multiple times.
Example:
[Form : FormName]
Part: part1, part2, part3
i.e. the part attribute takes multiple discrete values .In this example we cannot say Part:
part1, part2, part1
In dual list type attribute, discreteness is applicable only up to the first sub attribute level.
Thereafter the second sub attribute can have repeated values.
Example:
Set : Var1: “Value1”
Set : Var2: “Value1”
Here the first sub attribute has to be unique and discrete i.e., Var1 and Var2 whereas the
second subattribute i.e., Value1 can be same.
Same applies to triple list attribute type as well. Discreteness is applicable only up to first sub
attribute level.
2.2.3 Classification of Attributes
The attributes are classified based on the number of sub attributes it takes as values (separated
by “:”) i.e., either Single/Dual/Triple and the number of items (separated by “,”) to be
specified as a Value i.e., Single/List.

34
Definitions, Attributes & Modifiers

There are seven types of attributes:


 Single and Single List
 Dual and Dual List
 Triple and Triple List
 Menu Item List
 Event list

Figure 2.2 Attributes & Modifiers

The Attribute Type Single


In this type the attribute accepts only one sub attribute as a value. This value can be specified
only once. The single be stated only once per definition. If the attribute having attribute type
single is repeated then the definition will take the last value of the attribute, i.e. the previous
will be overwritten by the last value.
Example:
[Field: PartOne]
Width : 30
Width : 35
Width : 40
;;Width attribute takes a Single sub-attribute as “30”
The Width attribute is of type Single as it accepts only one sub attribute as value and this can
be specified only once.

35
Definitions, Attributes & Modifiers

Other examples of Single Attributes are: Set as, Set Always, Scroll and Title etc.

The Attribute Type Single List


In this type the attribute accepts only one sub attribute as a value and the value can be a list i.e.
multiple values can be specified for the attribute.
Example:
[Form: Hello]
Part : Hello Asia, Hello World
Part : Hello Universe
;;Part attribute takes a single sub-attribute as “Hello Asia”. Part is specified multiple times with different values.

The Part attribute is of Type Single List as it takes one subattribute as value and this value can
be repeated multiple times
Other examples of Single List Attributes are Part, Field, and Line etc.

The attribute type Dual


In this type the attribute accepts two sub attribute as a value. This value can be specified only
once.
Example:
Repeat : LineOne : CollectionLed
;;Repeat attribute takes the first sub-attribute as “LineOne” and the second sub attribute as CollectionLed

The Repeat Attribute is of Dual type as it takes two subattributes as value and the value can be
specified only once in a part.

The Attribute Type Dual List


In this type the attribute accepts two sub attribute as a value and the value can be a list i.e.
multiple values can be specified for the attribute.
Example:
Set : Var 1 : “Tally”
Set : Var 2 : “India”
;;The Set attribute takes the first subattribute as “Var1” and the second subattribute as “Tally”. “Set” is specified
twice with different set of subattributes.
The “Set” attribute is of Type Dual List as it takes two subattributes as value and this value can
be repeated multiple times

36
Definitions, Attributes & Modifiers

The attribute type Triple


In this type the attribute accepts three sub attributes as a value. This value can be specified
only once.
Example:
Object : Ledger Entries :First : $LedgerName = “Tally”
/* The Object attribute takes first subattribute as “Ledger Entries”, second subattribute as “First” and third subat-
tribute as “$LedgerName = “Tally”*/
The Object attribute is of Type Triple as it takes three subattributes as value and this value can
be specified only once.

The Attribute Type Triple List


In this type the attribute accepts three sub attributes as a value and the value can be a list i.e.
multiple values can be specified for the attribute.
Example:
Aggr Compute: TrPurcQty: Sum : $TrPurcQty
Aggr Compute: TrSaleQty: Sum : $TrSaleQty
Aggr Compute: TrQty : Sum : $BilledQty
/* The “Aggr Compute” attribute takes first subattribute as “TrPurcQty”, second subattribute as “Sum” and third
subattribute as “$TrPurcQty “.“Aggr Compute” is specified thrice with different set of subattributes. */
The Aggr Compute attribute is of Type Triple List as it takes three subattributes as value and
this value can be repeated multiple times

The attribute type Menu Item List


This is a special attribute type which does not fall into any of the categories given above.This
is because the no of subattributes to be specified is not constant.There are only three attributes
in TDL which fall under this category.The attributes are KeyItem, Item and Indent.
Syntax
The syntax of the attribute “Key Item” of Menu definition is as given below
Key Item : <DisplayName> : <HotKeyCharacter> : <Action> :
<Action Parameters>
Where,
<DisplayName> is a string will be displayed for the item added in the Menu.
<HotKeyCharacter> is a character which will activate the required action when it is pressed.
<Action> is an action to be performed ie it can either be a predefined Action or an Action
created using User Defined Function(Call keyword required in this case)
<Action Parameters> The parameter list separated by “:” based on the Action specified

37
Definitions, Attributes & Modifiers

Example:
[#Menu: Gateway Of Tally]
Key Item : Sales Analysis : S : Display : Sales Analysis
Key Item : Purchase Analysis: P : Display : Purchase Analysis
/* The attribute “Item” takes first subattribute as “Sales Analysis” second subattribute as the hotkey “S” and the
third subattribute as Action “Display” and the subsequent subattributes as parameters as required for the action
“Display”. The attribute can be specified twice with different set of subattributes.*/

The attribute Key Item is of Type Menu Item List where the no of subattributes for the value
vary based on the parameters for the Action and this value can be repeated multiple times.

The attribute type Event List


This is a special attribute type which does not fall into any of the categories given above.This
is because the no of subattributes to be specified is not constant. The attribute “On” enabled
for Event Handling is provided for the definitions Report,Form,Part,Line and Field falls under
the category of Event List.
Syntax
The syntax of the attribute “On” is as given below
ON : EventKeyword : <ConditionExpr>: <ActionKeyword>:
<Action Parameters>
Where,
<EventKeyword> can be any one of Events provided
<ConditionExpr> should return a logical value
<ActionKeyword> any one of the actions
<Action Parameters> parameters of the actions specified
Example:
[Form : TestForm]
On : FormAccept : Yes :HttpPost : @@SCURL : ASCII : SCPostNewIssue:
SCNewIssueResp
/*The attribute “On” takes first subattribute as the Event Keyword “Form Accept” second subattribute as the
condition “Yes” and the third subattribute as Action “HttpPost” and the subsequent subattributes as parameters as
required for the action “HttpPost”*/

The attribute On is of Type Event List where the number of subattributes for the value vary
based on the parameters for the Action and this value can be repeated multiple times. The list
of actions thus specified will be executed sequentially when the even occurs.

38
Definitions, Attributes & Modifiers

ON is a list type attribute, so list of actions can be executed sequentially when the specific
event occurs.
2.2.4 Predefined Attribute values in TDL
There are certain Attributes which take predefined values .The TDL programmer can make
use of them. The values accepted must be from the predefined set.
Example:
Scroll : Vertical
Scroll attribute accepts value Vertical, Horizontal and Both only. Some attribute accepts an
identifier as a value. The identifier is an existing definition name which is either available in
user defined TDL or in the default TDL.
Example:
Style : Normal
Style : Normal Bold
Style attribute takes name of style definition as a value. The style definition name can be user
defined.
Aliases for Definitions and Attributes
In TDL, we can refer to Defintions/Attributes with the same name. The synonymous names
are known as alias.
Definition Alias
Key and Button definition are Aliases.
Attribute Alias
Lines is an alias for Line. Similarly Part/Parts/ Top Parts, Field/Fields/Top Field etc. are alias
of the same attribute. Either can be used to get the same result
In a Part Definition a line can be assigned using the attribute “Line” as well as “Lines”. So, the
two Definitions (1 and 2) of a Part below are identical.
Definition – Default
In Default TDL, definition Default is defined for the definition types Menu, Report, Form,
Field and Collection. Some of the attributes predefined for the “Default” definition for each
definition type. Whenever a definition of this type is created, it inherits all the properties of
definition Default. We don’t have to explicitly mention these attributes.
Syntax
[<Definition Type> : Default]
Where,
<Definition type> is either of Menu, Report, Form, Field and Collection.
Example:
[Menu: Default]
Top Buttons:Select Company,Close Company,Blank Button,Change Date

39
Definitions, Attributes & Modifiers

Top Buttons:Change Menu Period,Second Blank Button,Change Company


Top Buttons:Create Company,Bottom Blank Button,TNetConnect Company
Top Buttons:TNet Disconnect Company
Bottom Buttons : Company Operations, Change Configuration
Border3D : Yes
Gradient : Yes
Option : MultiLingualSupportOpt : @@MultiLingualSupport
Toolbar Buttons : TallyNetButton, OnlineHelpButton, HelpButton
In the menu definition Default , all the tool bar buttons are defined.
[!Menu : MultiLingualSupportOpt]
Add : Toolbar Buttons : OutputLanguage, InputLanguage
[Report: Default]
PrintSet : Report Title : $$DescName
PrintSet : ReportSubTitle: ""
PrintSet : SVPrintCopies : 1
Variable : SVExport
;; Language Variables
Variable : SVCurrentUILanguageId, SVCurrentKBLanguageId
/*In the report definition Default , the print set values such as Report Title and subtitle and the number of copies to
print are specified .*/

[Form: Default]
Space Top : 0.5
Space Bottom : 0.5
Key : Form Delete, Form Cancel
XMLTag : "ENVELOPE"
Toolbar Buttons: FormOutputLanguage, FormInputLanguage
Toolbar Buttons: OnlineHelpButton, HelpButton, TallyNetButton
Bottom Toolbar Buttons : BottomToolBarBtn1
/*In the form definition Default, the spacing of .05 is specified. The Enclosing XML tag sent along with all the XML
formats from Tally is specified at Form Level. The toolbar buttons are also specified.*/

40
Definitions, Attributes & Modifiers

[Field: Default]
Space Left : 0.5
Space Right : 0.45
Show Table : On First Key
Lines : 1
Border3D : Yes
/* In order to display data in the field the Lines attribute is mandatory. The attribute is already specified in the field
definition Default, so when any field definition is created , it inherits this attribute value. The application developer
need not specify it again. */
Syntax
KBLanguage : <Language ID>
Where,
<Language Id> is language id in which the master is created. If the language id is specified
as 0 then all masters will be gathered other wise only maters created in provided language id
will be gathered.

[Collection: Default]
KB Language : If ##SVFilterMasterTableOnLanguage then +
##SVCurrentUILanguageId else 0
/*In collection definition Default only attribute specified is KB language. The attribute KBLanguage is used to
gather masters created in particular language id. */
2.2.5 Modifiers
Modifiers are used to perform a specific action on definition or an attribute. These are mainly
targeted to do bring in some changes to the existing Definition or Attribute.
Modifiers can be classified as
 Definition Modifiers – #, !, @ and *
 Attribute modifiers
Static/Load time modifiers – Use, Add, Delete, Replace/Change

Dynamic/Real time modifiers – Option, Switch and Local

Definition Modifiers
The modifiers that operate upon Definitions and are used to modify/alter some existing defini-
tions are referred to as definition modifiers.
Syntax
[<Modifier><Definition Type> : <Definition Name>]

41
Definitions, Attributes & Modifiers

Where,
<Modifier> is any one of the definition modifiers #, ! and *
<Definition type> is name of predefined definition types
<Definition Name> is any user defined name for the definition

Modifier ( # )
This is used to modify an existing definition. # can also be used to modify the [System :
Formula/Formulae] definition.
Example:
[#Menu: Gateway of Tally]
Here # is used to modify the existing menu “Gateway of Tally “
Modifier ( * )
This is used to re-initialize the definition i.e. all existing properties are not considered.
Whatever we provide as new attributes are only applicable. It is similar to modifying an
existing definition and deleting all its attributes and adding new ones.
[*Field: Sample ReInitialize]
Info :"Re Initialized - All the attribute values are deleted+
and newly defined
Border: Thick Box

Even the attributes that are inherited from default definition are removed. When
a field used for displaying data is re-initialized, the attribute Lines is manda-
tory.

Modifier (!)
This is used to define optional definition for an existing Definition. We can have multiple
options for the same definition based on a condition. The optional definitions can be defined
using the modifier “!” .We cannot refer to the optional definition directly from any other defi-
nition.
Example:
[Report : RepName]
Option: Rep1:##SVCurrentCompany=”Tally India”
Option: Rep2:##SVCurrentCompany=”Tally Solutions”

<report attributes>

42
Definitions, Attributes & Modifiers

[! Report:Rep1]
<report attributes>
[!Report:Rep2]
<Report Attributes>
;;When the current company is “Tally India” the report Rep1 will be displayed. The report Rep 2 is displayed if the
selected company is “Tally Solutions”. In any other case the report RepName will be displayed.

Attribute Modifiers
An attribute modifier is used to modify an existing defined attributes. There are two types of
attribute modifiers.
Static/Load time modifiers
The modifiers Use, Add, Delete, and Replace are referred as static modifiers. These modifiers
do not require any conditions to be evaluated at the run time. The value is evaluated at the load
time only and remains static throughout the execution.
Modifier (Add)
The ADD modifier is used in a definition to add an attribute to a Definition.

Example:
[Form: Cost Centre Summary]
Add : Button :ChangeItem
;;A new button “ChangeItem” is added to the form Cost Centre Summary.

Modifier (Delete)
The Delete modifier is used in a definition to delete an attribute from the Definition
Example:
[Form: Cost Centre Summary]
Delete : Button : ChangeItem
;;The button ChangeItem is deleted from the form Cost Centre Summary. The functionality of the button
ChangeItem is no longer available in the form Cost Centre Summary.

Modifier ( Replace)
The replace modifier is used in a definition to alter an attribute of the Definition
Example:
[Form: Cost Centre Summary]
Replace: Part : Part1: Part2
;;The part Part1 of form Cost Centre Summary is replaced by the Part2. Now only Part2 properties are applicable.

43
Definitions, Attributes & Modifiers

Modifier (Use)
The USE keyword is used in a definition to reuse an existing definition. After using the defini-
tion one can add or delete the attributes as required in the resultant definition.
Example:
[Field: DSPExplodePrompt]
Use : Medium Prompt
;;All the properties of the existing field definition Medium Prompt are applicable to the field DSPExplodePrompt.

Dynamic/Real time modifiers


The modifiers Option, Switch, Local are referred as dynamic modifiers. These modifiers get
evaluated at the run time based on a condition.

Modifier (Local)
The Local attribute is used in the context of the definition to set local value within the scope of
that definition only.
Example:
Local : Field: Name Field : Set As : #StockItemName
;;The value of the formula #StockItemName is now the new value for the attribute Set As of the field Name Field
applicable only for this instance.
Modifier (Option )
Option is an attribute which can be used by various definitions, to provide optional definitions
based on the condition.. The ‘Option’ attribute can be used in the Menu, Form, Part, Line, Key,
Field, Import File and Import Object definitions.
Syntax
Option : <Optional definition>: <Logical Condition >
<Optional Definition> is the name of optional definition created using the definition
modifier !.
<Logical Condition> if the ‘Logical’ value is set to ‘True’, then the ‘Optional definition’
becomes a part of the original definition and the attributes of the original definition are
modified based on this definition.
Example:
[Field: FldMain]
Option: FldFirst :cond1
Option: FldSecond :cond2
/* The field Fldfirst is applicable when the cond1 is true. The field Fldsecond is applicable when the cond2 is true.
Optional definitions are created with the symbol prefix "!" as follows*/
[!Field: FldFirst]
[!Field: FldSecond]

44
Definitions, Attributes & Modifiers

Figure 2.3 Modifier Option Evaluation

The attribute option compulsorily evaluates the conditions for all the options provided in the
definition code. All the definitions satisfying the evaluation conditions are applied to the
resultant definition. This means that it is not always easy to write the code where just want one
of the options to be applied, the programmer have to make sure that other options are not
applied using a negative condition. The new attribute Switch has been provided to support
these types of scenarios where evaluation is to be carried out only up to the point where the
first evaluation condition is satisfied
Modifier (Switch-Case)
Switch is attribute is similar to the Option attribute but reduces code complexity and improves
the performance. Once a condition is satisfied from one group, switch will not check further
conditions from the same group. It will evaluate the conditions from the other groups speci-
fied, if any.
The Switch are grouped using a label. Therefore, multiple switch groups can be created and
zero or one of the switch cases would be applied from each such group.

45
Definitions, Attributes & Modifiers

Apart from this, the switch can be grouped using a label, as shown below:
Syntax
Switch : Label : <Definition Name> : <Condition>
Switch : Label : <Definition Name> : <Condition>
Where,
< Label > is any string combination used to group,
< Definition Name > of same definition type in which the switch modifier is used,
< Condition > when true the optional definition will be used.

Figure 2.4 Switch case Evaluation

Example:
[Field: Sample Switch]
Set as : "Default Value"

46
Definitions, Attributes & Modifiers

Switch: Case1: Sample Switch1: ##SampleSwitch1


Switch: Case1: Sample Switch2: ##SampleSwitch2
Switch: Case2: Sample Switch3: ##SampleSwitch3
Switch: Case2: Sample Switch4: ##SampleSwitch4

[!Field : Sample Switch 1]


Set as : “Value from Sample Switch 1”

[!Field : Sample Switch 2]


Set as : “Value from Sample Switch 2”

[!Field : Sample Switch 3]


Color : Released Blue

[!Field : Sample Switch 4]


Color : Released Orange

Let’s say that the value of the two variables Sample Switch1 and Sample Switch3 are true. In
this case the field Sample switch will display text Value from Sample Switch 1 in Released
Blue color.

Sequence of Attribute and Modifier Evaluation


The final set of attributes applicable to the definition are evaluated based on the internal order
of evaluation of attributes and modifiers. The order of evaluation of the attributes and
modifiers is as specified as below:
1. Use
The Use attribute is evaluated first irrespective of the order where it is specified in the defini-
tion description.
2. Normal Attributes
Attribute that are not pre-fixed with an attribute modifier. The attributes are evaluated in the
order of specification.
3. Add/Delete/Replace

47
Definitions, Attributes & Modifiers

Add/Delete/Replace are referred to as Delayed attributes because even if they are specified
within the definition in the beginning their evaluation will be delayed till the end within static
modifier and normal attributes.
4. Option
The option conditions are evaluated on runtime based on the user selection.
5. Switch
The switch conditions are then evaluated on runtime based on the user selection.
6. Local
The local modifier is evaluated in the end, on runtime based on the user selection.
Example of Evaluation
Let us understand the execution of a TDL Program.
Exercise 2.1
Objective
The objective of this program is to render the text 'Hello World' at the Top and Hello Universe
at the bottom of the screen in 'Blue' Color.
Capabilities Used
 Attribute Modifier Use gets evaluated first in the sequence.
 Subsequently, other attributes get evaluated; hence the Width within 'Short Name
Field' is overridden with the Width Attribute specified in this Field.
 Since, Field Attribute 'Set As' is a single type attribute; the recent value will be set.
Hence, the value 'Hello World' overrides the value 'World'.
Code
[Report: Exer Seq of Eval]
Form : Exer Seq of Eval
Title : "Sequence of Evaluation"

[Form: Exer Seq of Eval]


Parts : Exer Seq of Eval

[Part: Exer Seq of Eval]


Lines : Exer Seq of Eval HW
Bottom Lines: Exer Seq of Eval HU

[Line: Exer Seq of Eval HW]


Fields : Exer Seq of Eval HW

48
Definitions, Attributes & Modifiers

[Field: Exer Seq of Eval HW]


Set as : "World"
/* Below 'Width' will be considered since the Width set from the Field 'Short Name Field' through the
Attribute Modifier 'Use' is evaluated first and subsequently, this Width is set. */
Width : 15
/* Below Attribute Modifier 'Use' will be evaluated first */
Use : Short Name Field
Color : Blue
Set as : "Hello World"
;; This 'Set as' overrides the previous 'Set as'

[Line: Exer Seq of Eval HU]


Fields: Exer Seq of Eval HW
/* Field 'Exer Seq of Eval HW' is reused in this line and locally set to 'Hello Universe' */
Local: Field : Exer Seq of Eval HW: Set As :+
"Hello Universe"
;;End-of-File

49
Definitions, Attributes & Modifiers

Output

The report displays two lines on the screen. The line Exer Seq of Eval HW is displayed at the
Top and the line Exer Seq of Eval HU at the bottom of the screen.
In the field Exer Seq of Eval HW, as the attribute modifier Use is evaluated first, the font
used is Arial, the Width is 15 and case is Title case. The Set As attribute is of type single so the
last value for the Attribute Set As overrides the previous Set As. The result Hello World is
displayed.
In the Line Exer Seq of Eval HU, the field Exer Seq of Eval HW is reused. The value
displayed in the field is locally set/ altered to Hello Universe. The width of the form is auto set
according to the width set in the Fields.

Exercise 2.2
Objective
The objective of this program is to render the text 'Hello World’ either in Full Height of the
Form or required content height within the Form on selecting the Button 'Alt + H'. In other
words, this program helps us control the Height of the Form on click of a Button.
Capabilities Used
The objective of this code is to understand :
 The Switch Case conditions and Optional Definition

50
Definitions, Attributes & Modifiers

 Form Attribute Full Height


 A glimpse of Variable & Button Definition which will be detailed in forthcoming
topics
Code
[Report: Exer Switch Case]
Form : Exer Switch Case
Variable : Exer SC FullHeight
Set : Exer SC FullHeight: No
Title : "Optional Definition using Switch Case"

[Form: Exer Switch Case]


Parts : Exer Switch Case
;; To attach Button to the current Form
Button : Exer SC Change Height
/* Switch checks for the conditions sequentially. If any condition gets satisfied, all the further switch state-
ments grouped within the same label 'Case Height' are ignored. */

Switch: Case Height:Exer SC Small Hello World: +


NOT ##ExerSCFullHeight
Switch: Case Height:Exer SC Full Hello World : ##ExerSCFullHeight
/* Optional Definition is prefixed with ! and since switch statements fall under Form Definition, it requires
an Optional Form Definition. The attributes under the below Optional Form 'Exer SC Small HelloWorld'
are set if the value of local variable 'ExerSCFullHeight' is set to No else the following Optional Form Defi-
nition 'Exer SC Full HelloWorld' will be considered. */
[!Form: Exer SC Small Hello World]
;; Displays the form with height required by the Parts
Full Height : No
[!Form: Exer SC Full Hello World]
;; Displays the form with FullHeight
Full Height : Yes

[Line: Exer Switch Case]


Fields: Exer Switch Case

51
Definitions, Attributes & Modifiers

[Field: Exer Switch Case]


Set as : if ##ExerSCFullHeight then "Hello World displayed+
in Full Height of the Form" else "Hello World+
displayed in required content Height"
;; Button Definition
[Button: Exer SC Change Height]
Key : Alt + H
Title : if NOT ##ExerSCFullHeight then "Full Height" else+
"Reqd Height"
/* Value of variable 'Exer SC Full Height' is set to NEGATION or NOT of its value which gives a toggle
behaviour on clicking the button. Everytime the user presses Key 'Alt + H' or activates this button, the
variable value 'Exer SC Full Height' is set to opposite of its current value, i.e., if it is Yes', pressing F1
changes it to 'No' and vice versa. */
Action : Set: Exer SC Full Height : NOT ##ExerSCFullHeight
;; Variable is defined of Type Logical

[Variable: Exer SC Full Height]


Type : Logical
;;End-of-life

Output

Figure 2.5 FullWidth Full Height Attributes

The above are the Output when the Logical Variable value Exer SC Full Height is No. On
clicking the button Full Height, the Variable value is set to Not of current Variable value.

52
Definitions, Attributes & Modifiers

Hence, the resultant Variable value is Yes and the below Output appears displaying Form with
Full Height and the Toggle Button Title changed to Reqd Height.

Figure 2.6 FullWidth FullHeight Attributes

In the Form Exer Switch Case, there are two Switch conditions based on Logical Variable
value Exer SC Full Height. Based on the satisfied condition, relevant optional Form gets
evaluated. Also, the Button Title and Field contents get altered based on the Variable value.

53
Chapter 3: Datatypes, Operators and
Expressions

3.1 Introduction
In the previous chapter we have discussed about the three basic components of TDL, Defini-
tions, Attributes and Modifiers. The primary focus of this chapter would be to understand the
various Data types and Operators available in TDL and how valid expressions are constructed.
Any information stored on Computer system is commonly referred as Data. Based on the value
that is refers to, the data is classified in to different types called as data type. For example, if the
value is 123, then the data type is Number. Data type specifies the type of value and the
validity constraint of each data type
3.2 Data Types
The Data is the lowest element of information. It exists in different forms as number, date etc.
A data type is a set of data with values having predefined characteristics. Data types supported
by computer languages vary from one language to another. The language usually specifies the
range of values for a given data type, how the values are processed by the computer, and how
they are stored.
The Data Types in TDL are used to specify the type of data stored in the field or a variable.
As we know that TDL is a business language it requires the support for various business data
types like amount, quantity, rate apart from the other basic types.

55
Datatypes, Operators & Expressions

Figure 3.1 TDL Data Types

Based on the requirements of the business the data types in TDL are classified in two catego-
ries: Simple and Compound.
3.2.1 Simple Data Types
The data types which can hold the data for a specific type only are referred to as Simple Data
Types. These cannot be further divided into sub types. Mentioned are the simple data types
available in TDL.
String
The string data type accepts alpha numeric characters as well as special symbols. There is no
restriction on the number of characters which can be accepted for this data type. If the restric-
tions are required that can be applied at the field level as per the scenario.
Example:
The name of the company ABC Company Ltd. can be stored in the string data type.

56
Datatypes, Operators & Expressions

Number
A number data type is used to store a numeric data only. The valid range acceptable in TDL is
from 92233720368547.7580 to +92233720368547.7580.
Example:
The phone number “98450 98450” can be entered in a number type field.
Date
This data type is used to store Dates. The valid range acceptable in TDL is from 1-1-1901 to
31-12-2098.
Example:
The date of purchase or payment can be displayed only in a field of type Date.
Logical
This data type is used to specify a logical value. It accepts Yes/ No, True/ False, On /Off and 0/
1.
Example:
The logical data type is mostly used in the configuration settings. The value of Explode flag is
No by default. It must be set to Yes in order to display exploded data.
3.2.2 Compound Data Type
In a business scenario the data may be a combination of multiple components. TDL provides a
comprehensive set of compound data types which consists of further subtypes.
Compound data types in TDL are: Amount, Quantity, Rate, Rate of Exchange.
Amount
This data type is a combination of subtype of Base/Direct Base, Forex, Rate and DrCr.
 Base/Direct Base – This subtype is used to specify the amount in the base currency
applicable for the particular company
 Forex – This subtype is used to specify the value of the amount in a foreign cur-
rency, as specified by the user.
 Rate – This subtype will be used to specify the Forex rate
 DrCr – This subtype is used to specify a “Dr” & “Cr” based on whether it is a Debit/
Credit amount.
The valid range acceptable in TDL is from -92233720368547.7580 to 92233720368547.7580
and the four decimal places are applicable for Base Amount and Forex based on the number of
decimal specified in the Currency master. Whereas for Forex, the decimal places can go to the
maximum of four decimal places which are independent of the number of the decimals
mentioned in the respective currency master.

57
Datatypes, Operators & Expressions

Example:
The opening balance of a Ledger from group Sundry Debtor is $1000. The base currency of
the company is Rupees and the Rate of Exchange is specified as $1/ Rs. 42.50. Now this infor-
mation is stored in the respective sub-types as follows:
Base : Rs. 42,500 ($1000 * 42.50)
Forex : $1000
Rate : Rs. 42.50/$
DrCr : Dr
Quantity
This data type comprises of the subtype base units/primary units, alternate units/ secondary
units and unit symbol.
 Base Units /Primary Units – The quantity along with the base unit is specified
using this data type.
 Alternate Unit/ Secondary Units –The quantity in alternate units is specified using
the sub type as Alternate units
 Unit symbol – The Unit symbol for the quantity is specified using this subtype.
The valid range acceptable in TDL for the quantity data is from -92233720368547.7580 to
+92233720368547.7580 and number of decimal places depends on the number of decimal
specified in the Unit master.
Example:
For a Stock item “Rice” the quantity is 10Bags and 2 kgs. The unit of measurement is 1 bag of
10 kgs. The alternate unit is specified as Grm and 1000gms = 1 kg.
Base Unit : 10 bags 2 kgs
Alternate Unit : 102000 gms
Unit Symbol : bag of 10 kgs
Rate
A rate data type is a combination of sub-types price, quantity & units symbol.
 Price – The Price of the item is specified using this sub-type.
 Quantity – This specifies the quantity for which the price is specified
 Units/Unit Symbol – This specifies the unit for which the price is specified
The valid range acceptable in TDL for the rate is from -92233720368547.7580 to
92233720368547.7580. The number of decimal places for Price depends on the number of
decimal specified in the Currency master and for Quantity it depends on the number of
decimal specified in the Unit master.

58
Datatypes, Operators & Expressions

Example:
The rate for a Stock Item is entered as Rs 100/5 nos
Price : 100
Quantity : 5 nos
Unit symbol : 5 nos
Rate of Exchange
This data type is used to specify the conversion rate between currencies. Acceptable range for
Rate of Exchange is from -92233720368547. 7580 to 92233720368547. 7580 and the decimal
places can go to the maximum of 4 which are independent of the number of the decimals
mentioned in the respective currency master.
Example:
If the conversion rate for $1 is Rs 45
Rate of Exchange : Rs 45/ $
Due Date
This data type is used to store a date range. It stores two date values From Date and To Date.
Only the To Date value is entered and the value of from date is determined by the system.

Example:
While entering a voucher in the credit period either number of days is entered or to date is
entered and from date is internally considered to be billed date.

Even though the data types Rate of Exchange and Due Date are compound data
types, they don’t have any sub-types .i.e. for these data types sub-types can’t be
specified explicitly.

The Field Attribute Type


The type for the field definition is specified using the Type attribute.
Syntax
[Field: <Field Name>]
Type : <Data type> : <Sub-type>
Where,
<Data Type> is primary data type name,
<Sub –Type> is name of sub-type belonging to the specified primary data type

59
Datatypes, Operators & Expressions

Example:
[Field: Qty Secondary Field]
Type : Quantity: Secondary Units
Data Type Formats
In TDL various formats are used are available to represent the data. Some Formats are applica-
ble only to a specific data type. The Field attribute Format is used to specify the format based
on the data type specified in the Type attribute of the field.

The Field Attribute Format


The type for the field definition is specified using the Type attribute.
Syntax
[Field: <Field Name>]
Type : <Data type>
Format : <List of Formats>
Where,
<Data Type> is primary data type name,
<List of Formats> is comma separated list of formats applicable for the <primary data
type>

Example:
The code to specify format for number ‘85.49’ to be displayed as (44.5%) is as follows:
[Field: NumField]
Type : Number
Format : Decimal: 1, Percentage, Bracketed

60
Datatypes, Operators & Expressions

The formats applicable for applicable data types Number, Amount, Quantity, Rate and Rate Of
Exchange are as follows:

Number Data Type and its Formats


The following table shows formats applicable data type Number with example:
Format Value of Field Value Returned
Comma 1000 (Default) 1,000

No Comma 1,000 1,000


Positive/Signed 1000 (positive (+) 1000
number by default)
Decimal: no of decimals 1000.19 1000.2 (Round
off)
No Zero 0.00 (Blank Field)
Percentage 1.00 1%
Bracketed 1.00 (1.00)

61
Datatypes, Operators & Expressions

Amount Data Type and its Formats


The following table shows formats applicable data type Amount along with example:
Format Value of Field Value Returned
Comma 1000 (Default) 1,000
No Comma 1,000 1,000
Positive/Signed 1000 (+ve number (+) 1000
by default)
Decimal: no of decimals 1000.19 1000.2 (Round off)
DrCr/CrDr 1000.00 1000.00 Dr
1000.00 Cr
Symbol/Currency 1000 Rs.1000
Show Base Currency 1000 Rs.1000
Forex 1200 $1200 if the amount is in foreign
currency in Dollars
All Symbols 1260 If the amount is converted to base
currency from other currency
then value returned is like
$30 @Rs.42/USD=Rs.1260
No Zero 0.00 (Blank Field)
No Symbol 1000.00 1000.00
Bracketed: For Negative -100 (100)

Quantity Data Type and its Formats


The following table shows formats applicable data type Quantity with example:
Format Value of Field Value Returned
Comma 1000 ((Default setting of 1,000
Number Type)
No Comma 1,000 1,000
SDF 1000 1000 for Cr Side
-1000 for Dr Side
Positive/Signed 1000 (Denotes a positive +(1000)
number by default in Tally)

62
Datatypes, Operators & Expressions

Decimal: No of 1000.19 1000.2 (Rounded off)


Decimals
DrCr/CrDr 1000 1000.00 Dr
1000.00 Cr
Units 750 750 kgs, 750 nos depending on
the units In which the entries
have been passed
TailUnits 10 Crtn 5 Box 3 Pcs 1253 pcs. Here it shows the least
unit(Pcs). All the cartons and
boxes get converted into Pcs
TailUnits:Box 10 Crtn 5 Box 3 Pcs 125 Box. All the cartons and
pieces get converted to Boxes
Shortform 10 crtn 5 box 3 pcs 10-5-3
No Compact 10Crtn 5 box 3 pcs 10- 5-3
No Zero 0.00 (Blank Field)

The field Format “No compact” has to be used along with “Shortform”.
Assuming the units of measure are set as 1 Carton = 12 box and 1Box =10 Nos

Rate and Rate of Exchange Data Type and its Formats


The following table shows formats applicable data type Rate and Rate of Exchange with
example:
Format Value of Field Value Returned
Comma 1000 ((Default setting of 1,000
Number Type)
No Comma 1,000 1,000
Positive/Signed 1000 (Denotes a positive +(1000)
number by default in Tally)
Decimal: No of 1000.19 1000.2 (Rounded off)
Decimals
DrCr 1000 1000.00 Dr/No.s
1000.00 Cr/No.s

63
Datatypes, Operators & Expressions

Units 750 750 kgs, 750 nos


TailUnits 10 Crtn 5 Box 3 Pcs 1253 pcs. Here it shows the least
unit(Pcs). All the cartons and
boxes get converted into Pcs
TailUnits:Box 10 Crtn 5 Box 3 Pcs 125 Box. All the cartons and
pieces get converted to Boxes
Shortform 10 crtn 5 box 3 pcs 10-5-3
No Compact 10Crtn 5 box 3 pcs 10- 5-3
No Zero 0.00 (Blank Field)

The unit is displayed based on the Unit of Measure of selected Stock Item.

Date and Due Date Data Type and its Formats


The formats applicable for applicable data types Date and Due Date are as follows:
Format Value Set in the Field Value Displayed after applying
Format
Short Date 22-Dec-1999 22-12-99
16-Mar-2000 16-03-2000
Long Date 22-Dec-1999 Wed, 22nd Dec, 1999
Universal Date 22-12-1999 22-Dec-1999
Month Beginning 01-12-1999 Dec – 99
04-12-1999 04-Dec-99
Month Ending 31-12-1999 Dec – 99
14-12-1999 14-Dec-99
3.2.3 Data Conversion (Type Casting)
Data conversion refers to changing one data type to the other. Converting the data of a given
type into another type is known as type-casting. Type casting is required when an expression
data is a combination of different data types. Each programming language has its own rules on
how types can be converted. Data conversion can be Implicit or Explicit.

64
Datatypes, Operators & Expressions

Implicit Data Conversion


Implicit data conversion is done automatically by the language compiler. In a mixed-type
expression, data of one or more subtypes can be converted to a super type as needed at runtime
so that the program will run correctly. Implicit conversion occurs from all data types to string
data type.
Consider following Examples:
Example:
[Field: Field1]
Type : String
Set As : 12345
The number is implicitly converted to String and will be displayed.
Example:
[Field: Clg Bal]
Type : Number
Set As : “1000”
In the above case the String 1000 will be automatically converted to number.
The following table shows the implicit conversion for Simple data types based on the value
specified in the field using SET AS attribute and the data type of the field specified using Type
attribute.
Set As Number Amount Rate of Quantity Rate Date Due- String Logical
Type Exchange Date
String Yes Yes Yes Yes Yes Yes Yes Yes Yes
Number Yes Yes Yes Yes Yes No Yes Yes No
Date No No No No No Yes Yes Yes No
Logical Yes No No No No No No Yes Yes
Consider following Examples:
Example:
[Field: Field1]
Type : String
Set As : 12345
The number is implicitly converted to String and will be displayed.
Example:
[Field: Clg Bal]
Type : Number
Set As : “1000”

65
Datatypes, Operators & Expressions

In the above case the String 1000 will be automatically converted to number.
The following table shows the implicit conversion for Simple data types based on the value
specified in the field using SET AS attribute and the data type of the field specified using Type
attribute.
i. Implicit conversion happens from Amount, Rate Of Exchange, Quantity
and Rate to Number data type when a method returning value in respec-
tive data type is used in Set As attribute. Otherwise an empty field is dis-
played.
Eg: [Field: NoToAmt]
Type : Number
Set As : $ClosingBalance

When the string specified in a Date field is in date format acceptable by


Tally.ERP9 like “06/06/2011”, “6-Jun-2011” etc. then implicit conversion is
done.
Eg. [Field: StrToDate]
Type : Date
Set As : “6-Jun-2011”

ii. In the Logical field, ONLY the number 0/1 are acceptable for No/Yes
respectively. If any other number is specified as value for a Logical field
then an empty field is displayed.
Eg. [Field: NoToLogical]
Type : Logical
Set As : 0
iii. When the string specified in a Logical field is any one of these True, False,
On, Off, Yes, No then implicit conversion is done.
Eg.[Field: StrToLogical]
Type : Logical
Set As : “True”

66
Datatypes, Operators & Expressions

Explicit Data Conversion


Explicit data conversion is required when the data types can’t be converted implicitly. For
example, converting string type to Amount needs explicit conversion. TDL provides different
functions to support data conversion e.g. $$AsAmount, $$AsQty, $$AsRate, $$Inwords,
$$Number, $$String etc. The function $$Date is used to convert string data to date.
Syntax
<Conversion Function> : <Value>
Example:
[Field: Clg Bal]
Type : Amount
Set As : $$AsAmount:“Rs.1000”
1,000.00 is displayed in the field as a result of above code assuming that Rupees is a valid
currency in the current company.
By default for the data types Amount and Rate the conversion is done based on the Base
currency and currencies set for the selected company; whereas for Quantity data type conver-
sion depends on the Unit of Measure of the selected Stock item.
Example:
[Field: Clg Bal]
Type : Amount
Set As : $$AsAmount:“1000”
1,000.00 is displayed in the field as a result of above code and by default the currency is con-
sidered as base currency of the current company.
Exercise 3.1:
Objective
The objective of this program is to render fields with various Data Types set in the Field.
Capabilities Used
 The Field attribute 'Type' is used to set the Data Type for the Field
 The other attributes used for report designing are Border, Style, Align, Width and
Info
 The function 'AsAmount' is used to convert a Number into Amount

67
Datatypes, Operators & Expressions

Code
[Report: Exer Data Types]
Form : Exer Data Types
Title : "Data Types"

[Form: Exer Data Types]


Parts : Form SubTitle, Exer Data Types
Local : Field: Form SubTitle: Info: "Understanding Data Types"
Width : 40% Page

[Part: Exer Data Types]


Lines : Exer Data Types Title, Exer Data Types
Border : Thin Box
/* Border is an attribute of Part, Line or Field which accepts the Definition Name of Type 'Border'. Border 'Thin Box' is
pre-defined within Default TDL */

[Line: Exer Data Types Title]


Use : Exer Data Types
Border : Thin Bottom
Local : Field: Default : Type: String
Local : Field: Default : Align: Center
Local : Field: Default : Style: Normal Bold
Local : Field: Exer DT String: Info: "String"
Local : Field: Exer DT Date: Info: "Date
Local : Field: Exer DT Number: Info: "Number"
Local : Field: Exer DT Amount: Info: "Amount

[Line: Exer Data Types]


Fields : Exer DT String, Exer DT Date, Exer DT Number, +
Exer DT Amount

68
Datatypes, Operators & Expressions

[Field: Exer DT String]


Type : String
Set As : "Keshav"
Border : Thin Right
/* Field Attribute 'Width' is used to set the Dimension for the Field. Specifying only Number without a Unit of Measure-
ment implies Number of Characters. */
Width : 10% Page
Align : Center

[Field: Exer DT Date]


Type : Date
Set As : "05-01-2010"
Width : 10% Page
Align : Center

[Field: Exer DT Number]


Type : Number
Set As : 1000
Width : 10% Page
Border : Thin Left Right
Align : Center

[Field: Exer DT Amount]


Type : Amount
Set As : $$AsAmount:1000
Width : 10% Page
Align : Center
/* 'AsAmount' is a platform Function which accepts a Numeric Value as its parameter andreturns it in Amount Format. */
;;End-of-file

69
Datatypes, Operators & Expressions

Output

Program Explanation
The report displays three lines on the screen. The title Understanding Data Types are
displayed by using the pre-defined field Form Subtitle.
The lines Exer Data Types Title and Exer Data Types are displayed after the Form Title line.
The line Exer Data Types Title displays names of various data types and line Exer Data
Types displays the respective values for each data type.
In the field Exer DT String, Exer DT Date, Exer DT Number and Exer DT Amount the
attribute Type is used to set the data type in the respective field as String, Date, Number and
Amount.
The attribute Align, Border and Width are used to create the table like format.
3.3 Operators in TDL
Operators are special symbols or keywords that perform specific operations on one, two, or
three operands, and then return a result.
The types of operators in TDL are as follows:
 Unary Operators
 Arithmetic Operators
 Logical Operators
 Comparison Operators
 String Operators

3.3.1 Unary Operators


The two unary operators supported by TDL are ” –“ and “%”.
 “% “ : It is used to specify the dimension in percentage of page or screen. It is also
used as pattern matching character
Syntax
<operand 1> %Screen/Page
Example:
[Part : Title]
Width : 20 %Screen

70
Datatypes, Operators & Expressions

This will allocate 20% of the screen space as width to the given Title part. ‘%’ as pattern
matching character means any character any number of times.
Syntax
%<String Value>
Example:
[Field : Test Fld]
Set As : If @@CMPMailName LIKE “%Ltd.” Then “Limited Company” +
Else “Public Company”
 “-“ : It negates the value of its operand. The data type of the result is same as its
operand.
Syntax
- <Operand>
Example:
[Field : Test Fld]
Use : Number Field
Set As : -100

3.3.2 Arithmetic Operators


The arithmetic operators supported by TDL are + (Addition), - (Subtraction), / (Division) and
* (Multiplication).
+ Addition
_ Subtraction
/ Division
* Multiplication
 “+”: The addition operator is used to add the two operands on either side of the oper-
ator.
Syntax
<operand 1> + <operand 2>
Example:
12345 + 6789
This will give the result as 19134.
 “- “: The subtraction operator is used to subtract the second operand from the first
operand.

71
Datatypes, Operators & Expressions

Syntax
<operand 1> - <operand 2>
Example:
12345 - 6789
This will give the result as 5556.
 “*” : The Multiplication operator is used to multiply the two operands on either side
of the operator.
Syntax
<operand 1> * <operand 2>
Example:
12345 * 6789
This will give the result as 83810205.
 “/” : The Division operator is used to divide the first operand by the second operand.
Syntax
<operand 1> / <operand 2>
Example:
12345 / 6789
This will give the result as 1.89.
3.3.3 Logical Operators
The logical operators used are:
OR Returns True if either of the operand is true
AND Returns True when both the operands are True
NOT Returns True if the operand value is False and False when operand value is
True
TRUE/ Can be used to check if the value of the operand is true.
ON/YES
FALSE/ Can be used to check if the value of the operand is false.
OFF/NO
 OR : Evaluates <operand1> and returns true if the operand evaluates to true. If
<operand1> evaluates to false, <operand2> is evaluated. If <operand2> evaluates to
false, the final result is false; otherwise, it is true.

72
Datatypes, Operators & Expressions

The result is true if either or both operands evaluate to true; the result is false only if both
operands evaluate to false. The OR operator can be used with any number of operands; if any
operand evaluates to true, the result is true.
The final value can be evaluated based on the following Table
<Operand 1> <Operand 2> OR
False False False
True False True
False True True
True True True
Syntax
<operand 1> OR <operand 2>
Example:
[System: Formula]
Explodable : $$KeyExplode OR @@FlagExplode
The value of Explodable is TRUE is any of the two argument returns the value as TRUE
otherwise the value is FALSE.
 “AND” : Performs an operation on the values of one or both of the operands. Eval-
uates <operand1> and returns false if the operand evaluates to false. If <operand1>
evaluates to true, <operand2> is evaluated. If <operand2> evaluates to true, the final
result is true; otherwise, it is false. And operator can be used with any number of
operands; the result is true only if all the operands are true else it is false.
The final value can be evaluated based on the following Table
<Operand 1> <Operand 2> AND
False False False
True False False
False True False
True True True

Syntax
<operand 1> AND <operand 2>
Example:
[System: Formula]
IsBatchWiseOn : $IsBatchWiseOn AND $$IsBatchWiseOn

73
Datatypes, Operators & Expressions

The value of the formula IsBatchwiseOn is set to true only if the values of method $IsBatch-
WiseOn and function $$IsBatchWiseOn both are true otherwise false is set.
 “! / Not” : the Not operator reverses the value of the operand. If operand is a value is
true, the value of !<operand> is false. In short NOT TRUE returns false and NOT
FALSE returns true.
The final value can be evaluated based on the following Table:
<Operand> Not
False True
True False
Syntax
NOT <operand> / ! <operand>
Example:
[System: Formula]
SimpleCompany : NOT $IsAggregate
The value of the formula SimpleCompany is true if the value of Method $IsAggregate is false
 True/ On / Yes: Any of the keyword True/ On /Yes can be used in the conditional
operands as it is or for comparing values.
Syntax
TRUE / On / Yes
Example:
[Field: MyField]
Type : Amount
Set As : If True Then $$AsAmount:“Rs.1000” Else $$AsAmount:”500”
The 1,000.00 is displayed in the field as a result of above code.
 False/ Off/ No: Any of the keyword False/ Off / No can be used in the conditional
operands as it is or for comparing values.
Syntax
FALSE / Off / No
Syntax
[Field: MyField]
Type : Amount
Set As : If False Then $$AsAmount:”Rs.1000” Else $$AsAmount:”500”
The 500.00 is displayed in the field as a result of above code.

74
Datatypes, Operators & Expressions

3.3.4 Comparison Operators


A comparison operator compares its operands and returns a logical value based on whether the
comparison is true. The comparison operator returns value as true or false. TDL supports
following comparison operators:
= /Equal/ Equals Checks if the values of both the operands
are equal
< / Less Than / Lesser Checks if the value of the <operand 1> is
Than / Lesser less than the value of <operand 2>
> / Greater Than/ More Checks if the value of the <operand 1> is
greater than the value of <operand 2>
In Checks if the value is in the List of comma
separated values
Null Checks whether the operand is Empty
Between...And Checks if the operand value is in the range
 = /Equal/ Equals: The value TRUE is returned if both the operands are equal.
Syntax
<operand 1> =/Equals/Equal <operand2>
Example:
Break On : $$Line = 1
My formula : $BasicTypeOfDuty:Ledger:$LedgerName Equals +
$$LocaleString:“Sales Tax”
 < / Less Than / Lesser Than / Lesser: The value TRUE is returned if the
<operand1> is less than the <operand2>.
Syntax
<operand 1> </Less Than/Lesser <operand2>
Example:
$$Line < $$NumItems:AllLedgerEntries
 >/ Greater Than/ More: The value TRUE is returned if the <operand1> is greater
than the <operand2>.
Syntax
<operand 1> >/Greater Than/More <operand2>
Example:
$$Line > $$NumItems:AllLedgerEntries

75
Datatypes, Operators & Expressions

 In / One: The value TRUE is returned if the <operand1> is in the List of comma sep-
arated values, otherwise false is returned.
Syntax
<operand 1> In (<list of values>)
Example:
Set As: If #Myfield IN (100,200,300) then 200 else 500
 Null: The value TRUE is returned if the <operand1> is empty, otherwise false is
returned.
Syntax
<operand 1> Null
Example:
Set As: If #Myfield Null Then 200 Else 500
 Between …. And: The Between ... And operator returns True, if the value of <oper-
and> is between <Lower limit> and <Upper Limit> (inclusive); otherwise, it returns
False. The Not logical operator can be included to evaluate the opposite condition.
Syntax
<operand> Between <Lower limit> And <Upper Limit>
Example:
If #Myfield Between 50 And 150 Then 200 Else 500
3.3.5 String Operators
A string operator allows comparing two strings. The following are the string operators:
Contains/ Containing Checks if the operand contains given
string
Starting With / Checks if the operand starts with the given
Beginning With/ Starting string
Ending With / Ending Checks if the operand ends with given
string
Like Checks if the operand matches with the
given string pattern

 Contains/ Containing: The string operator Contains alias Containing returns Yes if
the <operand1> string has a string <operand2> else No is returned.
Syntax
<operand1> Contains/Containing <operand 2>

76
Datatypes, Operators & Expressions

Example:
Set As: “Hello TDL” Contains “TDL”

 Starting With / Beginning With/ Starting: The string operator Starting with alias
Beginning With returns Yes if the <operand2> starts with <operand1> string else No
is returned.
Syntax
<operand1> Starting With/Starting/Begins <operand 2>
Example:
Set As: If “TDL World” Starting with “TDL” Then “TDL” Else “World”
Set As: If “TDL World” Beginning “TDL” Then “TDL” Else “World”

 Ending With / Ending: The string operator Ending With alias Ending returns Yes if
the <operand2> ends with <operand1> string else No is returned.
Syntax
<operand1> Ending With/Ending <operand 2>
Example:
Set As: If “World TDL” Ending with “TDL” Then “TDL” Else “World”

 Like: Like operator uses “%” as a pattern matching character. % means zero or
more characters.
Syntax
<operand1> Like <%operand 2>
Example:
Set As: If $Name Like “%Party” Then “Debtors” Else “Creditor”

The operator = is a comparison operator, not assignment operator. There is no


assignment operator in TDL.

3.3.6 Operator Precedence


The expression value is evaluated based on the following operator precedence:
1. Arithmetic Operator
Division or Multiplication

77
Datatypes, Operators & Expressions

Addition or Subtraction
2. Logical Operators
NOT

AND

OR

3. Comparison Operators
The precedence is in the order of their appearance in the expression.
4. String Operators
The precedence is in the order of their appearance in the expression.
The default operator precedence can be overridden by enclosing the expression in Brackets/
parenthesis. The expression in parenthesis is evaluated first.
3.3.7 Data Types supported by Arithmetic Operators
The arithmetic operators + (Addition), - (Subtraction), / (Division) and * (Multiplication) are
applicable to all Data Types. The following table specifies the data types of two operands and
whether arithmetic operations can be performed or not:
Operand 1 Number Amount Rate of Quantity Rate Date Due-
Exchange Date
Operand 2
Number Yes Yes Yes Yes Yes Yes Yes
Amount Yes Yes Yes Yes Yes No No
RateEx Yes Yes Yes No No No No
Qty Yes Yes No Yes Yes No No
Rate Yes Yes No Yes Yes No No
Date Yes No No No No No Yes
Due Date Yes No No No No Yes Yes

i. For data type Date ONLY addition and subtraction is supported


ii. For the data type String ONLY addition is supported

Exercise 3.2
Objective
The objective of this program is to accept two numbers/strings and compare them.

78
Datatypes, Operators & Expressions

Capabilities Used
The If Then Else Conditions are used for comparing the Strings/Numbers and display the
result accordingly.
The expression for comparison uses
 Logical Operator OR
 Numerical Operators >, <
 String Operators EQUALS, CONTAINS
 Function 'String' to convert the parameter to String Type
Code
[Report: Exer Operators]
Form : Exer Operators
Title : "Operators"

[Form: Exer Operators]


Parts : Form SubTitle, Exer Operators Num, Exer Operators Str
Local : Field: Form SubTitle: Info : "Working with Operators"
Width : 40% Page

[Part: Exer Operators Num]


Lines : Exer Operators, Exer Operator Result Num

[Line: Exer Operators]


Fields: Name Field, Exer Op Input1, Exer Op Input2
Local : Field: Default: Style: Normal
Local : Field: Name Field: Info: "Please enter two Numbers :"

[Field: Exer Op Input1]


Use : Number Field
Set As: 10
Border: Thin Box

[Field: Exer Op Input2]


Use : Number Field

79
Datatypes, Operators & Expressions

Set As: 12
Border: Thin Box

[Line: Exer Operator Result Num]


Fields : Exer Op Result Num
Space Top : 1
Local: Field: Default: Style: Normal Bold

[Field: Exer Op Result Num]


Set As:If @NonEmptyChk then "" else if #ExerOpInput1 >+
#ExerOpInput2 then @N1GrN2 else if #ExerOpInput1+
< #ExerOpInput2 then @N1LeN2 else @N1EqN2
/* Attribute 'Set Always' if enabled refreshes the field if the field/variable value on which this field is dependent are
effected or modified. */
Set Always: Yes
/* Attribute 'FullWidth' sets the maximum width available within the Form and Align : Centre attribute aligns it to the
Center of the Form. */
FullWidth: Yes
Align : Center
Skip : Yes
;; Local Formulae within Field 'Exer Op Result Num'
NonEmptyChk: $$IsEmpty:#ExerOpInput1 OR+
$$IsEmpty:#ExerOpInput2
N1 Gr N2 : $$String:#ExerOpInput1 + "is greater than" +
$$String:#ExerOpInput2
N1 Le N2 : $$String:#ExerOpInput1 + " is Lesser than " +
$$String:#ExerOpInput2
N1 Eq N2 : "Both the numbers are equal"

[Part: Exer Operators Str]


Lines : Exer Operators, Exer Operator Result Str
Local : Line : Exer Operators : Local : Field : Name Field: +
Info : "Please enter two Strings:"

80
Datatypes, Operators & Expressions

Local : Line : Exer Operators : Local: Field : Default : +


Type : String
Local : Field: Exer Op Input1: Set As: "String"
Local : Field: Exer Op Input2: Set As: "ing"
SpaceTop : 1

[Line: Exer Operator Result Str]


Fields : Exer Op Result Str
Local : Field: Default: Style: Normal Bold
Space Top: 1

[Field: Exer Op Result Str]


Use: Exer Op Result Num

/* String Operator 'CONTAINS' is used to compare two strings and return if one contains the other. Similarly, 'EQUALS'
is used to compare two strings and returns if both the strings are equal. */
Set As:If @NonEmptyChk then ""else if #ExerOpInput1+
EQUALS #ExerOpInput2 then @EqualStr else +
if #ExerOpInput1 CONTAINS #ExerOpInput2then +
@S2PartOfS1 else if #ExerOpInput2 CONTAINS +
#ExerOpInput1 then @S1PartofS2 else @ElseMsg
;; Local Formulae within Field 'Exer Op Result Str'
EqualStr : "Both strings are equal"
S2PartOfS1: #ExerOpInput2 + " is part of " + #ExerOpInput1
S1PartOfS2: #ExerOpInput1 + " is part of " + #ExerOpInput2
ElseMsg : "There is no relation between both the strings"
End-Of-File

81
Datatypes, Operators & Expressions

Output

Program Explanation
The report is displayed in edit mode five lines on the screen. The title Working with
Operators is displayed by using the pre-defined field Form Subtitle.
The line Exer Operators is used to accept two numbers and the line Exer Operator Result
Num is used to display the result after comparing the two numbers. The numbers for compari-
son are entered in the fields Exer Op Input and Exer Op Input2 and the logical operator OR
is used to check if any of these two is empty. The comparison operator > and < are used in the
If statement to check which number is greater than the other and display the result accordingly.
Similarly in the field in the line Exer Operator Result Num uses the attributes Set As to
display the result after evaluating the specified string expression. The string operator 'CON-
TAINS' is used to compare two strings and return if one contains the other and 'EQUALS' is
used to compare two strings and returns if both the strings are equal.
The attribute Set Always is used to display the result immediately.
3.4 Expressions in TDL
Expression is combination of operands and operators. A valid TDL expression is a combina-
tion of an operand and operator, where an operand can be either a field/variable value, method/
function/formula evaluation result, constant/keyword/identifier. In the expression a constant
can be of type String, Logical or Number. The compound data types i.e., Date, Quantity,
Amount and Rate are not supported as Constants. The key words used in the expression can
be any of the pre-defined values and Identifier always accepts a name of the definition which
can be in turn derived from an expression.
We will be taking up the various types of expressions and expression evaluation at the end of
the subsequent chapter “Access Specifiers & Special Symbols”.

82
Chapter 4 : Access Specifiers and
Special Symbols

Introduction
In the previous lesson, we have discussed the various Data types, Operators and Expressions
used in TDL. In TDL, few symbols are used for specific purposes and some symbols are used
as Access Specifiers i.e., mainly used to access value of a method, variable, field, formula etc.
Some symbols are used for a general purpose such as modifiers. Let us refer to the table below
to understand the categorization of the various symbols and their usage at a glance.
Access Specifiers

Symbols Usage
@ Used to access Local formula
@@ Used to get the value of a System formula
# When prefixed to Field name gives the value of the field
## Used to get the value of a global variable
$ Used to access the value of an Object Method
$$ Used to call the Function
Special Symbols

Symbols Usage
Definition
Modifiers
* Used to Reinitialize a Definition
! Used to create an Optional Definition
# Used as a definition modifier
Code Diffren-
tiator
; ;; ;;; /* */ Used for adding comments in TDL

83
Definitions, Attributes & Modifiers

+ Used as line continuation character


ODBC
Context
_ (underscore) Used to expose methods to ODBC and for creating SQL
Procedure
4.1 Access Specifiers
As we have already covered in the previous chapter, TDL expression is a combination of an
operand, operator and constant, where an operand can be either a field/variable value, method/
function/formula evaluation result. We have a specific set of symbols in TDL, which are
required to be prefixed to a name in order to determine what it refers to and extract/access
value from them therein.
The access specifiers determine the access to the names that follow it, ie., formula, method and
variable name. In this section, we are emphasizing on the usage of different access specifiers.
The access specifiers available in TDL are @, @@,#,##,$ and $$.
4.1.1 Usage of @ and @@
In TDL, large complex calculations can be broken down to smaller simple calculations or
expressions referred to as a Formula. The values computed using these formulae can be
accessed using the symbol prefixes @ and @@.
4.1.2 Naming Conventions for Formulae
Like other programming languages, we follow certain naming conventions in TDL as well.
The TDL Formulae are:
 Case sensitive
 Only alphanumeric characters are allowed
 Space insensitive at definition time. However, during the deployment or usage of
the same, spaces are not allowed

4.1.3 Classification of Formulae


In TDL the formulae are classified into Local Formula and Global Formula.
 Local Formula can be defined and retrieved at a specific Definition level
 Global Formula can be accessed across all definitions
Let us see how to access Local Formula and Global Formula in TDL

4.1.4 Accessing a Local Formula using @


As discussed, it is defined and retrieved at a specific definition level. The scope of the local
formula is only within the current definition. A local formula is usually defined if the formula

84
Definitions, Attributes & Modifiers

is specific to a definition and not required by any other definition. The value of a Local
Formula evaluation can be accessed using the Symbol Prefix @.
Example:
[Field: CompanyNameandAddress]
Set as : “Tally India Pvt Ltd, No 23 & 24, AMR Tech Park II,+
Hongasandra, Bangalore”
The above can be written, using the Local Formula as:

[Field: CompanyNameandAddress]
Set as : @Company + @Address + @City
Company : “Tally India Pvt Ltd,”
Address : “No 23 & 24, AMR Tech Park II, Hongasandra, ”
City : “Bangalore”

In the above example Company, Address and City are the formula names and specific values
are assigned to it. The "Set as" attribute is used to set the value of the field by evaluating the
concatenation of local formulae Company, Address and City by using the symbol @.

4.1.5 Accessing of Global Formula using @@


A Global Formula is one which when defined once, is available globally across definitions. In
other words, the Global Formula value can be accessed by all the definitions. A Global
formula is defined when a formula same formula needs to be evaluated at various definitions.
The value of a Global Formula can be accessed using the symbol prefix @@. A Global
Formula can also be referred to as a system formula. All the Global Formulae must be defined
within the [System: Formula] definition.

Example:
[System: Formula]
BackgroundColor:”Green”
AmountWidth :20

[Field: RepTitleAmt]
Color: @@BackgroundColor

[Field: RepDetailAmt]
Width: @@AmountWidth

85
Definitions, Attributes & Modifiers

Color: @@BackgroundColor

[Field: RepTotalAmt]
Width: @@AmountWidth
In the example mentioned above, all the fields assume the same width and the same back-
ground color. If the width of the fields need to be altered, a change is made only at the
[System: Formula] section. This change will be applied to all the Fields using the Global
Formula AmountWidth and BackgroundColor.

4.1.6 The Usage of #


In TDL, the Symbol Prefix # can be used for referencing a field value.

Referencing a Field value using #


The symbol prefix # is used to retrieve the value entered in a particular Field. Consider the
following example:
Example:
[Field: HW]
Set as: “Hello World”
[Field: HW1]
Set as: #HW
In the example mentioned above, the value within the Field HW is being set to the Field HW1.
In other words, the content of the Field HW i.e., The Field HW1 is set to “Hello World” by
using #HW.

4.1.7 The Usage of ##


In TDL, the symbol Prefix ## is used to access the value from a variable. The following
section gives an overview about TDL variables. The complete Variable Framework will be
dealt with in detail in the subsequent chapters.

Overview of a Variable in TDL


In General, Variable is a meaningful name of data storage location in computer memory.
Variables in TDL (Tally Definition Language) are entities, which can hold values during the
execution of a program. The values of these variables are initialized when it is created and can
change during the entire execution of program. Program can change the variable value by
specifying expressions which are evaluated and the value of the variables which are set.
Variable can hold a single value, or more than one value of same type or even different types.
It can be declared at various scopes such as Report, Function and System Level. Variables in

86
Definitions, Attributes & Modifiers

TDL are categorized based on the type and the number of values they can hold. The various
types of variables are:
 Simple Variable
 Simple Repeat Variable
 Compound Variable
 List Variable
Now we can look into these variable types in detail.

Simple Variable
Simple variables are used to store single value of the specified data type

Simple Repeat Variables


The Simple Repeat Variables are used to store multiple values of the same data type. These
values can be accessed via an implicit index framework from the field, when field is repeated.
Simple repeat variables can be used in columnar reports.

Compound Variable
Compound Variables allow the user to store multiple values of same or different data types.
This is achieved by making the variable itself compound, by allowing variable declaration
inside itself. These sub variables are called member variable of the main variable.

List Variable
List variables can store multiple values of the specified variable type by using a string based
‘Key’ specification. List Variable is a container ie; data structure which holds elements. List
variables are by default sorted on the insertion order. List variables further divided into
Simple List variable and Compound List Variable.
 Simple List Variable
Simple List Variables can hold multiple values of single data type.
 Compound List Variable
Compound List Variables can hold multiple values of different data types.
Both Simple and compound list variables can be declared as a list.

How to define a variable


A variable definition is also similar to any other definitions in TDL. The desired outcome
from a variable is determined by specifying the various attributes of the variable.
Syntax
[Variable: <Variable Name>]
Attribute : Attribute Value

87
Definitions, Attributes & Modifiers

where,
<Variable Name> is the meaningful name for the variable
Attribute is the name of the attribute
Attribute Value is the value to be assigned to the specified attribute

In TDL Variables are defined as simple or compound. In a variable definition if a Type


attribute is specified then it is a simple variable holding single type of value. For simple
variables type can be String, Number, Logical and Date etc. Similarly, in a variable definition
if one or more ‘Variable’ or ‘List Variable’ attribute is used then it has a member variable
and it becomes a compound variable.

Example:Simple Variable
[Variable : SimpleVar]
Type : Date
In the above example the variable SimpleVar holds the data type of Date is defined

Example: Compound Variable


[Variable : CompoundVar]
;;Simple Variable
Variable : Name : String
Variable : EmpId: String
;; Compound Variable
Variable : EmpDetails
;; Compound List Variable
List Variable : Address

[Variable: EmpDetails]
Variable : PhoneNo : Number
Variable : BloodGroup: String

[Variable : Address]
Variable : HouseNo : String
Variable : StreetName: String
Variable : Place: String
In the above example the attributes Variable and List Variable defines the compound variable.
Here Name and EmpId are Simple variables and Emp Details and Address are Compound

88
Definitions, Attributes & Modifiers

variables which are defined as members. A separate definition is required for the compound
variable Emp Details and Address.

Declaration and the scope of a variable


A variable does not exist until it is declared. The declaration of the variable determines the
availability and accessibility of the variable at various levels.
This is referred to as the variable scope. TDL variables can be declared at various scopes. The
scope of a variable can be System, Report and Function.
System
Variables declared at system level will start its life when the application starts, and it will be
alive till the application end. The variables declared at system scope are accessible every-
where in the system unless it overridden with another scope.
Example:
[Variable: SystemVar]
Type : Logical

[System: Variable]
SystemVar : No
Or
[System: Variable]
Variable:SystemVar
Report
Variables can be declared at report definition and it will be having the report scope. These
variables exist till the life of the report. The variables declared at report scope are accessible
from the report itself and all TDL elements which are executed form within this report such as
another report, function etc.
Example:
[Variable: ReportVar]
Type : Logical
[Report: Report Scope]
Variable: Report Var

Function
As we discussed earlier Function is an important component in TDL language. User Defined
functions are used to create procedures by TDL programmer, if it is required to execute a
certain set of statements repeatedly to achieve a certain functionality. Since Function is a TDL
component, it also allows the variables to be declared at its scope. Function variables has
lifetime till the end of the execution of the function.

89
Definitions, Attributes & Modifiers

Example:
[Function: FunctionVar]
Variable : FuncVar1
List Variable: FuncVar2

Accessing value from a Variable using ##


The value of a Variable can be accessed using symbol prefix ##. This operator is prefixed with
variable specification. Consider the following example:

Example:
;;Variable Definition
[Variable: ReportVar]
Type : Logical

;;Variable declaration
[Report: Report Scope]
Variable: Report Var
;; Accessing the variable
[Field: Report Scope]
Option : Report Scope Red BG: Not ##ReportVar
Option : Report Scope Green BG: ##ReportVar

Here we are accessing the value of a variable at the Report Scope by using the operator ##.
Similarly ## operator is used on a compound variable it returns the first member variable
value. If it is used on a list variable it returns the number of items in the list.
This operator is allow dotted notation syntax to access the member of compound variables and
also it support index operator to access the value of elements in list variable directly. This will
be covered in detail along with complete Variable Framework in subsequent chapters.

4.1.8 Usage of $ and $$


This is the third set of access specifiers. $ is used to access the value of a method and $$ is
used to call an internal/user defined function

4.2 Overview of a Method


In TDL each piece of information stored in the data object can be retrieved using a method. A
method either performs some operation on the object or retrieves a value from it. Methods are
classified as Internal or External methods.

90
Definitions, Attributes & Modifiers

Internal Methods
The methods which are defined by the platform are called as Internal Methods. For example
the methods Name, Address, Parent are the internal Methods of Object Ledger.

User Defined/External Methods


Methods defined by the user are referred to as External methods or User defined methods.

Accessing Method value using $


The value of a method can be accessed by using the symbol prefix $. Both internal and
external methods can be accessed by using $
Example:
[Field: My Field]
Set as: $Name

The previous code snippet displays the value of the method Name of the associated object. As
we already know that the objects in TDL follows a hierarchical data structure. It is possible to
extract information from any level by using the dotted syntax. “$” also supports dotted
notation syntax for the same. This will be dealt with in detail in the Chapter “Objects,Collec-
tions & Internal Object Structure”.

4.3 Functions in TDL


A function is a small code which accepts a certain number of parameters performs a task and
returns the result. The function may accept zero or more arguments but returns a value. In
TDL prior to Tally.ERP 9 Functions were defined by Platform and TDL programmer could
only call the function to achieve certain functionality. From Tally.ERP 9 onwards functions
can be defined in TDL as well.These are defined using the definition “Function”. This can
either return a value or can be designed to perform only a set of Actions without returning a
value.
In built functions are meant to be used by the TDL programmer and are specifically designed
to cater to the business requirement of the Tally.ERP 9 application.
4.3.1 Accessing a Function using $$
Any TDL function can be accessed by using the symbol prefix $$. Both platform and user
defined functions returning a valuecan be accessed by using $$.

User Defined Functions which does not return a value are called using the
keyword “Call”.

91
Definitions, Attributes & Modifiers

Example:
[Field: Current Date]
Set as : $$MachineDate
[Field: Credit Amt]
Set as : if $$IsDr:$ClosingBalance then 0 else $ClosingBalance
[Field: StringPart Field]
Set as : $$StringPart($Email:Company:##SVCurrentCompany):0:5
Exercise 4.1
Objective
The objective of this program is to understand the usage of different access specifiers in TDL.
The access specifiers available in TDL are @, @@,#,##,$ and $$.

Capabilities Used
Variable attribute is used to define or declare the value of a Variable
 Accessing values of Local formula as well as System formula
 TDL functions like $$String, $$IsBillwiseOn
 Usage of Tooltip attribute
Code
[Report: Exer Symbols]
Form : Exer Symbols
Title : "Usage of Symbols"
;; Variable is declared of Type 'String' and an initial Value 'Variable Value' is set to it within this Report.
Variable: Exer Symbols Var1 : String: "TallySolutions Pvt Ltd."
Variable: Exer Symbols Var2 : Number: 9000
Object : Company: ##SVCurrentCompany

[Form: Exer Symbols]


Parts : Form SubTitle, Exer Symbols Info, Exer Symbols
Local : Field: Form SubTitle: Info: "Usage of Symbols"
Width : 100% Page

[Part: Exer Symbols Info]


Lines : Exer Symbols Info
Space Bottom: 1

92
Definitions, Attributes & Modifiers

[Line: Exer Symbols Info]


Fields : Info Field
Local: Field: Info Field: Info : "Hover your mouse over the Field+
Value columns to view further description"
Local: Field: Info Field: FullWidth: Yes
Local: Field: Info Field: Style: Normal Italic
Local: Field: Info Field: Align: Center

[Part: Exer Symbols]


Lines :Exer Symbols Title1, Exer Symbols Title2, Exer Symbols@,+
Exer Symbols@@, Exer Symbols#,Exer Symbols##, Exer Symbols$,+
Exer Symbols$$
CommonBorder: Yes

[Line: Exer Symbols Title1]


Fields : Medium Prompt
Right Fields : ExerSymbols Orig Info, ExerSymbols Reused Info
Local : Field: Default: Style: Normal Bold
Local : Field: Default: Align: Center
Local : Field: Medium Prompt: Info: ""
Local : Field: ExerSymbols Orig Info: Info: "First Field"
Local : Field: ExerSymbols ReusedInfo: Info: "Second Field"
Local : Field: ExerSymbols Orig Info: Border: +
Right Sub Column Titles
Local : Field: ExerSymbols ReusedInfo : Border: +
Right Sub Column Titles
Local : Field: ExerSymbols Orig Info : Width: 80% Page
Local : Field: ExerSymbols ReusedInfo : Width: 80% Page
Local : Field: ExerSymbols Orig Info : SubTitle : Yes
Local : Field: ExerSymbols ReusedInfo : SubTitle : Yes
Border : Thin Top

93
Definitions, Attributes & Modifiers

[Line: Exer Symbols Title2]


Use : Exer Symbols@
Local: Field: Default: Style: Normal Bold
Local: Field: Default: Align: Center
Local: Field: Medium Prompt: Info: ""
Local: Field: ExerSymbols Orig Info: Info:"Particulars"
Local: Field: ExerSymbols ReusedInfo:Info:"Particulars"
Local: Field: Exer Symbols Orig: Info: "Value"
Local: Field: Exer Symbols ReUsed: Info: "Value"
Border: Thin Bottom

[Line: Exer Symbols@]


Fields : Medium Prompt
Right Fields : ExerSymbols Orig Info, ExerSymbols Orig, +
ExerSymbols Reused Info, ExerSymbols Reused
Local : Field: Default : Style : Normal
Local : Field: Medium Prompt: Style: Normal Bold
Local : Field: Medium Prompt: Delete: Align
Local : Field: Medium Prompt: Info: "Symbol @"
Local : Field: Medium Prompt: Width: 20% Page
Local : Field: ExerSymbols Orig Info: Info: "Local Formula"
Local : Field: ExerSymbols ReusedInfo: Info: +
"Local Formula from first Field"
Local : Field: ExerSymbols Orig`: Set As: @ExerAdd1 + ", +
"+@ExerAdd2+ ", " + @ExerCity+ ", " + @ExerState
/*Since the Local Formula 'ExerAdd1', 'ExerAdd2', 'ExerCity', 'ExerState' are local to the Field 'Exer Symbols Orig',
same will not be accessible to this Field. Hence, the value set in this Field will be blank.*/
Local : Field: ExerSymbols Reused : Set As : @ExerCity + ", " +
@ExerState
Local : Field: ExerSymbols Orig : Tooltip : "Local Formulae+
accessed in Original Field where they are declared"

94
Definitions, Attributes & Modifiers

Local : Field: ExerSymbols Reuse : Tooltip :"Local Formulae of+


Original Field accessed in Reused Field which+
is not accessible"
Space Top : 0.25
Border : Thin Bottom

[Field: ExerSymbols Orig Info]


Use : Name Field
Lines: 0
Width: 30% Page

[Field: ExerSymbols Orig]


Use : Name Field
Lines : 0
Border : Thin Left
;; These Local Formulae can be used only within this Field 'Exer Symbols @'
Exer Add1: "#90, Mahaveer Apts."
Exer Add2: "Rajaji Path, 3rd Lane"
Exer City: "Thane-421210"
ExerState: "Maharashtra"
Width : 50% Page

[Field: ExerSymbols Reused Info]


Use : Name Field
Lines : 0
Width : 30% Page

[Field: ExerSymbols Reused]


Use : Name Field
Width : 50% Page
Lines : 0
Border : Thin Left

95
Definitions, Attributes & Modifiers

[Line: Exer Symbols@@]


Use : Exer Symbols@
Local : Field: Medium Prompt: Info: "Symbol @@"
Local : Field: ExerSymbols Orig Info: Info: "System Formula"
Local : Field: ExerSymbols ReusedInfo: Info: "System Formula"
/*System or Global Formula 'ExerAdd1', 'ExerAdd2', 'ExerCity', 'ExerState' can be used across any definitions. Hence,
both the fields 'Exer Symbols @@' and 'Exer Symbols @@ Reused' can use these Formulae*/
Local : Field: ExerSymbols Orig: Set As: @@ExerAdd1 + ", " +
@@ExerAdd2 + ", " + @@ExerCity + ", " +@@ExerState
Local : Field: ExerSymbols Reused: Set As: @@ExerAdd1 + ", " +
@@ExerAdd2 + ", " +@@ExerCity + ", " + @@ExerState
Local : Field: ExerSymbols Orig: Tooltip: "System Formula +
accessed in Original Field"
Local : Field: ExerSymbols Reused: Tooltip: "System Formula +
accessed in Reused Field"
;; These Local Formulae can be used only within this Field 'Exer Symbols @'
[Line: Exer Symbols#]
Use : Exer Symbols@
Local : Field: Medium Prompt: Info: "Symbol #"
Local : Field: ExerSymbols Orig Info: Info:"Value Set in first+
Field"
Local : Field: ExerSymbols ReusedInfo : Info: "First Field+
Value extracted here"
Local : Field: ExerSymbols Orig: Set As: "Tally.ERP9"
Local : Field: ExerSymbols Reused: Set As: #ExerSymbolsOrig
Local : Field: ExerSymbols Orig: Tooltip: "Original Field Value+
is set as Tally.ERP9"
Local : Field: ExerSymbols Reused: Tooltip: "Original Field+
Value is extracted in Reused Field using Symbol Prefix #"

[Line: Exer Symbols##]


Use : Exer Symbols@
Local : Field: Medium Prompt : Info: "Symbol ##"
Local : Field: ExerSymbols Orig Info: Info: "Variable Value 1"
Local : Field: ExerSymbols ReusedInfo : Info: "Variable Value 2"

96
Definitions, Attributes & Modifiers

;; Value from a Variable 'ExerSymbolsVariable' is extracted using Symbol Prefix ##.


Local : Field: ExerSymbols Orig: Set As: ##ExerSymbolsVar1
Local : Field: ExerSymbols Reused: Set As: $$String:+
##ExerSymbolsVar2
Local : Field: ExerSymbols Orig :Tooltip :"Value of the Variable+
'ExerSymbolsVar1'is accessed here using Symbol Prefix ##"
Local : Field: ExerSymbols Reused: Tooltip: "Value of the+
Variable'ExerSymbolsVar2' is accessed here using+
Symbol Prefix ##"

[Line: Exer Symbols$]


Use : Exer Symbols@
Local : Field: Medium Prompt : Info: "Symbol $"
Local : Field: ExerSymbols Orig Info: Info: "Company Name"
Local : Field: ExerSymbols ReusedInfo : Info: "Company Email"
/* Method 'Name' extracts the value from the Method 'Name' within the Object 'Company'since Report is associated with
the Company Object.*/
Local : Field: ExerSymbols Orig: Set As: $Name
/* Method 'Email' extracts the value from the Method 'Email' within the Object 'Company', since Report is associated with
the Company Object.*/
Local : Field: ExerSymbols Reused: Set As: $EMail
Local : Field: ExerSymbols Orig: Tooltip: "Company Name is +
extracted from Company Object using Symbol Prefix $"
Local : Field: ExerSymbols Reused: Tooltip: "Company Email is+
extracted from Company Object using Symbol Prefix $"

[Line: Exer Symbols$$]


Use : Exer Symbols@
Local : Field: Medium Prompt: Info: "Symbol $$"
Local : Field: ExerSymbols Orig Info: Info: "$$IsBillWiseOn"
Local : Field: ExerSymbols ReusedInfo: Info: "$$IsInventoryOn"
/* Function 'IsBillWiseOn' checks whether 'Maintain BillWise' Feature is enabled in the current Company and returns
logical value*/
Local : Field: ExerSymbols Orig: Set As:$$String:$$IsBillWiseOn
Local : Field: ExerSymbols Reused: Set As: $$String:+
$$IsInventoryOn

97
Definitions, Attributes & Modifiers

Local : Field: ExerSymbols Orig: Tooltip: "Function +


'IsBillWiseOn'is triggered using Symbol Prefix +
$$ which returns whether BillWise Feature is+
enabled or the Company"

Local : Field: ExerSymbols Reused: Tooltip: "Function +


'IsInventoryOn' is triggered using Symbol Prefix+
$$ which returns whether Company is created with+
Inventory enabled"
[System: Formula]
;; System or Global Formula can be used globally anywhere
Exer Add1 : "#180, Brigade House"
Exer Add2 : "J.P.Nagar, 2nd Phase"
Exer City : "Bengaluru"
Exer State: "Karnataka"
;; End-of-File

Output

Program Explanation
The output shows the usage of all the access specifiers. In the report, the part Exer Symbols
defines some lines which show the titles for the columns.

The Line Exer Symbols Title1 is used to show the main titles for the report. Further each
column divides into two to display titles for the value of field and its description for both fields
by using the line Exer Symbols Title2. The attributes Style, Border, Align, Width, Subtitle
etc are used to format the report or report values.

98
Definitions, Attributes & Modifiers

The Lines Exer Symbols@, Exer Symbols@@, Exer Symbols#, Exer Symbols##, Exer
Symbols$, Exer Symbols$$ includes four different fields called ExerSymbols Orig Info,
ExerSymbols Orig, ExerSymbols Reused Info, ExerSymbols Reused which are used to
display the values using various special symbols. These fields are locally modified in each line
by using the attribute modifier Local. Exer Add1, Exer Add2, Exer City, Exer State are the
system formulae which can be used anywhere in the program.
The attribute modifier Use is used at Line Exer Symbols$$ to reuse the properties of the
existing definition Exer Symbols@. The attribute Tool tip is enabled for the entire value
field.

4.4 Frequently used functions in TDL


The following are the frequently used internal functions in TDL. The following function cate-
gories
4.4.1 Type Casting Functions
$$String
This function converts the expression, which passed as parameter to a string.
Syntax
$$Stsring : <expression>
Where, expression is any valid TDL expression

Example:
$$String: $$MachineDate
In the above example, this function accepts machine date as parameter and it will be convert-
ing to the string data type.
$$Number
This function converts the given parameter into a valid number data type. It takes an expres-
sion and returns a numeric value. The value contains only four digits after decimal.
Syntax
$$Number:<expression>
Where, expression is any valid TDL expression
Example:
[System: Formula]
ActualRate : $Amount / $$Number:$ActualQty
In the above example the Number value is extracted from Actual Qty to divide Amount.

$$Date
The function $$Date is used to convert a date specified in string format into the "Date" data
type. This is mainly required when a string contains a date on which manipulations are to be

99
Definitions, Attributes & Modifiers

performed treating it as a date format eg: filtering the data based on the date comparison. TDL
allows Addition or subtraction of a number to a date type field and in turn, it will return a date
type field.
Syntax
$$Date : <String Expression>
Where, expression is any valid TDL expression
Example:
Set as : $$Date:$JoiningDate
In the above example the method joining date will return a date to $$Date as parameter.
$$Date function converts this date to date format.

$$AsAmount
This function is used to convert data types of the value from one form to amount type. This
function states the calculated value as an Amount.
Syntax
$$AsAmount:<expression>
Where, expression is any valid TDL expression
Example:
[Field: AmtFld]
Use : Amount Field
Set as : $$AsAmount:$BasicRateOfInvoiceTax
In the above example, "BasicRateOfInvoiceTax" is of type Number and to display the same in
Amount Field, it is being converted to Amount Type using the function $$AsAmount.

$$AsQty
This function treats the quantity received as Inward Quantity.
Syntax
$$AsQty:<expression>
Where, expression is any valid TDL expression
Example:
[Field: AsQty]
Use : Qty Primary Field
Set as : $$AsQty:$Amount

In the above example, Amount is of type Amount and to display the same in Quantity Field, it
is being converted to Quantity Type using the function $$AsQty.

100
Definitions, Attributes & Modifiers

4.4.2 Mathematical Functions


Mathematical Functions can be used to perform common mathematical operations such as
Total, SubTotal etc.

$$Total
This function is used to total all the values in a specific column for a particular field. The
column of the Field being totaled could be a Quantity or Amount or a Number. The Fields
being totaled need to be specified in the Part Definition with attribute ‘Total’ apart from the
actual definition of the field. The Expression/Field values should be Amount/Number/
Quantity type.
Syntax
$$Total:<Field Name>
Example:
[Field: FieldTotal]
Use : Number Field
Set as : $$Total: SCRAmount
In the above example the field definition ‘FieldTotal’ and totals the "SCRAmount” field
values and display the final total in the “FieldTotal” field.

$$SubTotal
The Sub Total function is exactly like the Total function except that it is a running total for that
column and appears on individual Lines and not on the total lines, hence the individual lines
will need to use a defined Subtotal field. The Expression Field should be Amount/Number
Type. i.e., input should be numerical field. Return type will be Amount.
Syntax
$$SubTotal:<Field Name>
Example:
[Field: BillSubOp]
Use : BillOp
Set as : $$SubTotal:BillOp
In above Example the $$SubTotal will give the total of field BillOp

$$PrevFldTotal
The function $$PrevFldTotal is used to extract the total value of the previous fields. This is
useful in Multi column reports. It does not accept any parameter and returns a value of type
same as the type of previous fields. This function doesn’t take any parameters

101
Definitions, Attributes & Modifiers

Syntax
$$PrevFldTotal
Example:
[Field: DSP Perc]
TotPercVal : ($$AsSignedQty:$$PrevFld / $$Number: +
$$AsSignedQty: $$PrevFldTotal) * 100
4.4.3 Logical Functions
$$DoExplosionsFit
In case of printing, if a line is exploded then this function can be used to check whether the
exploded part fits in the given page. It returns logical expression Yes if it is true.
Syntax
$$DoExplosionsFit
Example:
[Line:EXPINVInvDetails]
Explode : EXPINVBatchDetails
NextPage : NOT $$DoExplosionsFit OR (($$LineNumber = +
$$LastLineNumber) AND $$IsLastOfSet)
This function can be used to print the line in the next page, with attribute Next Page in line.

$$IsDr
This function is used to check if the amount is a Debit amount.
Syntax
$$IsDr : <amount expression>
Example:
[Field: DrAmt]
Use : Logical Field
Set as : $$IsDr:$OpeningBalance
In the above example function returns "Yes" if "OpeningBalance " is a Debit amount else it
returns "No".

$$IsEven
This function checks whether the numeric value passed as a parameter is Even number or not.
If the given input is an even value the function will return "Yes" otherwise it will return "No".

102
Definitions, Attributes & Modifiers

Syntax
$$IsEven:<number>
Example:
[System: Formula]
NumVal : $$Number:25
ChkEvenNumber : $$IsEven:@@NumVal
In the above example, the system formula ‘ChkEvenNumber’ will return ‘No’.
$$IsGroupCash
This function is used to check if the group belongs to Cash-in-Hand or not.
Syntax
$$IsGroupCash: <string expression>
Where, String expression is any TDL expression, which returns string data type value
Example:
[System: Formula]
IsCashLedger : $$IsGroupCash:$Parent:Ledger:$Name

$$IsLedger
To check if the current object is of type "Ledger".
Syntax
$$IsLedger
Example:
Display : Ledger Monthly Summary : $$IsLedger
$$IsPayment
This function is used to check if the Voucher Type is Payment or not.

Syntax
$$IsPayment : <string expression>

Example:
Set as : if $$IsPayment:$VoucherTypeName then +
$$AsCrAmt:$Amount else $$AsDrAmt:$Amount
In the above example the Credit Amount is displayed if the voucher type name is Payment
otherwise it displays Debit Amount.

103
Definitions, Attributes & Modifiers

4.4.4 Date Functions


$$DateTo
This function returns the date with which the period ends. This is particularly useful when it is
required to compare given date with the end date of the period.
Syntax
$$DateTo
Example:
SVToDate : $$DateTo
$$DayOfDate
This function returns only the day from a complete date in number format. This date is
converted to number so that some computation can be performed on this.
Syntax
$$DayOfDate: <date expression>
Example:
DayOfTo : $$DayOfDate:$$PeriodDateTo

$$DayofWeek
This function returns the day of the specified date e.g., Monday. This function returns the
weekday of the date specified. The Parameter can be any expression (i.e.,Formula / Storage/
variable etc) in date format.
Syntax
$$DayOfWeek:<date expression>
Example:
Set as : $$DayOfWeek:$$CurrentDate
Function 'DayOfWeek' extracts the day of the week from the specified date ie; Current Date

$$MonthStart
This function returns the first day of the specified month.
Syntax
$$MonthStart:<date expression>
Example:
Set : SVFromDate : $$MonthStart:##SVCurrentDate
The above example will set the first day of the specified month to SVFromDate.

104
Definitions, Attributes & Modifiers

$$WeekEnd
This function gives the first Sunday’s Date. If the argument itself (Date) is a Sunday then it
will return the following Sunday.
Syntax
$$WeekEnd:<date expression>
Example:
Set : SVFromDate : $$WeekEnd:##SVCurrentDate
The above example will set the first Sunday’s date for the specified to SVFromDate.

Exercise 4.2
Objective
The objective of this program is to demonstrate the process of extracting value from the TDL
Functions using Symbol '$$'. The various date functions used in the program to extract the
value of current date, Day of the week, month and so on. Functions accept zero or more
parameters, processes and returns some value, this code also introduces some date related
functions.
Capabilities Used
 Using the $$ symbol to extract the value from the function

Code
[Report: Exer Date Functions]
Form : Exer Date Functions
Title : "Date Functions"
Auto : Yes

[Form: Exer Date Functions]

Parts : Form SubTitle, Exer Date Functions


Local : Field: Form SubTitle: Info: "Date Functions"
Local : Field: Default: Skip: Yes
Local : Field: Default: Set Always: Yes
Local : Field: Long Prompt: Width: 15
Local : Field: Exer DF Current Date: Skip: No
Local : Field: Exer DF Current Date: Set Always: Yes
Local : Field: Exer DF Day of Week: Skip: No

105
Definitions, Attributes & Modifiers

Local : Field: Exer DF Day of Week: ReadOnly: Yes


Width : 25% Page

[Part: Exer Date Functions]


Lines : Exer DF Current Date, Exer DF Day of Week, +
Exer DF Day of Date, +
;; Symbol '+' in this context is a line continuation character
Exer DF Month of Date, Exer DF Short Month of Date, +
Exer DF Year of Date
[Line: Exer DF Current Date]
Fields : Long Prompt, Exer DF Current Date
Local : Field: Long Prompt: Info: "Current Date :"
Space Bottom: 1

[Field: Exer DF Current Date]


Use : Uni Date Field
/*Function 'MachineDate' displays the machine or system date. For e.g., 3-Feb-2009. The initial value for this field is set
as Machine Date and user can alter to check the impact on other fields.*/
Set as: $$MachineDate
Width : 12
Align : Left
Border: Thin Box

[Line: Exer DF Day of Week]


Fields : Long Prompt, Exer DF Day of Week
Local : Field: Long Prompt: Info: "Day of Week :"

[Field: Exer DF Day of Week]


Use : Short Name Field
/*Function 'DayOfWeek' extracts the day of the week from the parameter of Type 'Date' specified. In this case, another
function 'CurrentDate' itself is given as a parameter, which returns the date selected by the user. For e.g., Tuesday*/
Set as : $$DayOfWeek:#ExerDFCurrentDate

[Line: Exer DF Month of Date]


Fields : Long Prompt, Exer DF Month of Date

106
Definitions, Attributes & Modifiers

Local : Field: Long Prompt: Info: "Month :"


[Field: Exer DF Month of Date]
Use : Short Name Field
/* Function 'FullMonthName' extracts the month name from the parameter of Type 'Date' specified and displays it in full.
For e.g., February*/
Set as : $$FullMonthName:#ExerDFCurrentDate

[Line: Exer DF Short Month of Date]

Fields : Long Prompt, Exer DF Short Month of Date


Local : Field: Long Prompt: Info: "Short Month :"

[Field: Exer DF Short Month of Date]


Use : Short Name Field
/*Function 'ShortMonthName' extracts the month name from the parameter of Type 'Date' specified and displays it in
short. For e.g., Feb*/
Set as: $$ShortMonthName:#ExerDFCurrentDate

[Line: Exer DF Day of Date]


Fields : Long Prompt, Exer DF Day of Date
Local : Field: Long Prompt: Info: "Day of Date:"

[Field: Exer DF Day of Date]


Use : Short Name Field
/* Function 'DayofDate' extracts only the Date portion from the parameter of Type 'Date' specified. For e.g., 15 */
Set as: $$DayofDate:#ExerDFCurrentDate

[Line: Exer DF Year of Date]


Fields : Long Prompt, Exer DF Year of Date
Local : Field: Long Prompt: Info: "Year of Date:"

[Field: Exer DF Year of Date]


Use : Short Name Field
/*Function 'YearofDate' extracts only the Year portion from the parameter of Type 'Date' specified. For e.g., 2010*/
Set as: $$YearofDate:#ExerDFCurrentDate
;; End-of-File

107
Definitions, Attributes & Modifiers

Output

Program Explanation
The above report is displayed by using default TDL functions. The line Exer DF Current
Date extracts the current date by using the function $$MachineDate and this function accepts
zero parameters. Similarly, the function $$DayOfWeek returns the day of week and this
fuction accepts the value of the field #ExerDFCurrentDate.

The formatting of this report is done by using the attributes Align, Width, Border etc. The date
format also fixed by using the attribute modifier Use and the value of the same inherits the
format, which is defined in the default TDL.

4.5 Special Symbols


4.5.1 Usage as Definition Modifiers
Modifying existing definitions using #
In the above section, we have seen that # is used to refer the field. Another usage of # is to
modify existing definitions. So the user can alter the attributes of the modified definition. For
e.g., adding a new Field within a Line definition.
Example:
[#Menu: Gateway of Tally]
Add : Key Item: Hello World: H : Display: HWReport
Title: “Tally Gateway”
[#Field: LedParticulars]
Width: 50
In the above example, the existing Menu Gateway of Tally (default Menu) has been altered to
add the Item ‘Hello World’ and the Title of the Menu is changed to Tally Gateway. The
existing Field LedParticulars have also been altered to set its width attribute to the value of 50.

108
Definitions, Attributes & Modifiers

ReInitialize Definitions using (*)


When * is used for an existing definition; all the attributes of the definition are overridden.
This is very useful when there is a need to completely replace the existing description content
with a new code.
Example:
[*Field: MyField]
Width : 20% Page
Set as : “This Field has been reinitialized”
Optional Definitions using !
The Symbol Prefix ! is used to define optional definitions. Switch and Option are attributes
which can be used by various definitions like Menu, Form, Part, Line, Field, Collection,
Button, Key, Import File and Import Object to provide a conditional result in TDL. However,
they cannot be used with Report, Color, Style, Variable, System Formula, System Variable,
System UDF, Border and Object definitions. The attributes of the original definition are over-
ridden by the attributes of the optional definition only if the Logical Condition is satisfied. In
other words, if the Logical Condition returns True, the attributes of the optional definition
become a part of the original definition else it is ignored, leaving the original definition intact.
Syntax
Option : <Optional Definition> : <Logical Condition>
Switch : Label : <Optional Definition> : <Logical Condition>
The difference between Switch and Option is that Switch statements bearing the same label
are executed till a satisfying condition is found. On the other hand, option executes all the
Option statements matching the given conditions sequentially. Switch statements bearing
different labels are similar to Option statements as all the Switch statements will be executed
for the given conditions.
Example:Option
[Line: MFTBDetails]
Fields : MFTBName
Right Fields: MFTBDrAmt, MFTBCrAmt
Option : MFTBDtlsClsgG1000 : $ClosingBalance > 1000
Option : MFTBDtlsClsgL1000 : $ClosingBalance < 1000

[!Line: MFTBDtlsClsgG1000]
Local : Field : MFTBDrAmt : Style : Normal Bold
Local : Field : MFTBCrAmt : Style : Normal Bold

109
Definitions, Attributes & Modifiers

[!Line: MFTBDtlsClsgL1000]
Local : Field : MFTBDrAmt : Style : Normal
Local : Field : MFTBCrAmt : Style : Normal

In the above code snippet, the condition specified in both the options, will be checked and it
will execute the option satisfying the given condition. In this case, there is a possibility that
more than one condition might satisfy and get executed.
Example:Switch
[Line: MFTBDetails]
Fields : MFTBNameRight
Fields : MFTBDrAmt, MFTBCrAmt
Switch : Case 1: MFTBDtlsClsgG1000 : $ClosingBalance > 1000
Switch : Case 1: MFTBDtlsClsgL1000 : $ClosingBalance < 1000

[!Line: MFTBDtlsClsgG1000]
Local: Field : MFTBDrAmt : Style : Normal Bold
Local: Field : MFTBCrAmt : Style : Normal Bold

[!Line: MFTBDtlsClsgL1000]
Local: Field : MFTBDrAmt : Style : Normal
Local: Field : MFTBCrAmt : Style : Normal

In the previous code snippet, the condition specified in the switch statements, will be checked
one after another. The first statement satisfying the given condition will be executed and all
other statements grouped within this label, ‘Case 1’ will not be executed further unlike Option.
The similar behavior of Option can be achieved by specifying different labels, if required.

4.5.2 Usage as Code Differentiators


Commenting a Code using ;, ;; and /**/
We humans are in a habit to keep a note of everything, which remind us to keep a follow-up of
all the things we need to keep a track off. In the same way, TDL gives us flexibility to put a
comment inside the code at any place where there is a possibility of confusion. Now, following
are few useful tips to write a comment.

There are three formats to write a comment in TDL language. They are as follows:

110
Definitions, Attributes & Modifiers

Semicolon ( ; )
This is used for commenting a part from a line.

Example:
; Altering Menu Gateway of Tally
[#Menu: Gateway of Tally]
Add: Key Item: Comment: C: Display : Comment
Double semicolon ( ;; )
This is normally used for Single Line Commenting. Put a double semicolon in every line
before the starting of comments
Example:
;; Altering Menu Gateway of Tally
[#Menu: Gateway of Tally]
Add: Key Item: Comment: C: Display : Comment
Enclose a comment within /* */
This is used for multi line commenting. Start a comment with a single backslash with an
asterick ( /* ) and then at the end of the comment put an asterick with a single backslash ( */ ).
A comment can be split over more than one line
Example:

/* This code explains the usage of Multi-Line Commenting as well as Single Line Commenting.*/

[#Menu: Gateway of Tally] ; Altering Menu Gateway of Tally


Add: Key Item: Comment: C: Display : Comment
;; Menu Item alteration ends here

Dictionary hints using ;;;


The Literal String Hint (;;;) Tally being Unicode compatible, Literal String Hint helps the
Str2Xml utility to identify the $$LocaleString parameters based on the comment passed
through the ;;; expression.
Example:Literal String

Help: Info : $$LocaleString :"( Alt. Units)" ;;; Stock Reports-+


Show Qty in Alternate Units??
In this example, the string “Stock Reports - Show Qty in Alternate Units??” appears as the
comment with the string “Alt. Units” in the output generated using Dictionary Manager utility.
Accordingly, this helps to find the context in which the string is used, so that the string can be
converted to corresponding language in the same context.

111
Definitions, Attributes & Modifiers

Line Continuation Character (+)


A Line Continuation Character (+) is used to split a lengthy line into number of shorter lines.
By doing this, the programmer can see the entire line without scrolling to the left or right. This
can also help in understanding and debugging the code faster.
Example:
/* This code explains the mechanism of breaking a line into Multiple Lines using +
*/
;; Altering Menu Gateway of Tally
[#Menu: Gateway of Tally]
Add : Key Item : Before : @@locQuit : +LineCtn : C : Display :+
LineCtn : NOT $$IsEmpty : $$SelectedCmps
4.5.3 Usage in ODBC Context
Exposing Methods using using ( _)
The Symbol Prefix (_) is used to expose Methods to ODBC. Threafter these methods will be
available in the list of methods when Tally Database is accessed through ODBC Interface.

Example:
;; Exposing Methods within the Objects to ODBC
[#Object: Ledger]
_Difference: $ClosingBalance - $OpeningBalance
Creating SQL procedures using ( _ )
By prefixing _ to a Collection Name, it turns into a procedure which can be referenced exter-
nally by passing the parameter as a Variable. Creating Procedures to be referenced externally

Example:

[Collection: _LedBills]
Type : Bills
Child of : #UName
SQLParms : UName
SQLValues : Bill No : $Name
SQLValues : Bill Date : $$String:$BillDate:UniversalDate

You will be in a better position to understand the above when we discuss the
same in subsequent chapter “ODBC Interface”.

112
Definitions, Attributes & Modifiers

4.6 Valid Expressions in TDL


A valid TDL expression is a combination of an operand and operator where an operand can be
either a field/variable value, method/function/formula evaluation result,constant/keyword/
identifier. We have already covered the usage of Access Specifiers which are required to be
prefixed to a name in order to determine what it refers to and extract/access value from them
therein in the preceding section.
We will now consider a few examples of valid expressions in TDL.
Example:1
[Field: MyField]
Set As : ‘Hello World‛
In this code snippet ‘Hello World’ is the constant
Example: 2
[Field: MyField]
Type : Amount
Set As : If ##MyAccBal < 0 then ‘Low Balance‛ else ##MyAccBal
In the code snippet the value of a variable ‘MyAccBal’ is used in the evaluation of the expres-
sion.
Example:3
[Field: MyField]
Border : Thin Top
In the code snippet, ‘Thin Top’ is the identifier which refers to the definition name of type
Border.
Example:4
[System : Formula]
BooksFromDate : $BooksFrom:Company:##SVCurrentCompany
In the code snippet the ‘BooksFrom’ is a method of ‘Company’ object and ‘SVCurrentCom-
pany’ is the variable which stores the name of selected company. The formula returns the
Books beginning date of the current company.
Example:5
[System : Formula]
StartDate:$$Max:$$SystemPeriodFrom:$StartingFrom:Company:##SVCurrentCompany

Function Method Object Variable

In the code snippet the function access the value of the method ‘StartingFrom’ of the object
‘Company’ based on the value of the variable ‘SVCurrentCompany’.

113
Definitions, Attributes & Modifiers

Example:6
[System : Formula]
PrintLangName : $$FilterValue:@@LangNameInUILangauge:Languages:+
First:PrintLangConfigFilter
In the code snippet the function ‚$$FilterValue‛ retrieves the first matching value from the
Language collection for the value of the method
Example:7
[Field: CV Dep Variable]
Use : Name Field
Table : CV List Child Collection
Set As : $$CollectionField:$Name:2:CVListChildCollection
In the code snippet the function ‚$$CollectionField‛ retrieves the method $Name from the
second object of the collection ‚CVListChildCollection‛

TDL Expression Evaluation


An expression in TDL is always evaluated in context of the Interface (Requestor) and the Data
Object Associated with the Interface object. At this point it may be difficult to understand the
Object Context, which will be covered in detail in the Chapter ‚Objects, Collections & Internal
Object Structure‛. However, in order to put this in a simpler way.
 We already know that Report contains a Form, Form a Line and so on. Based on this
a complete Interface Object hierarchy is created.
 Whenever we are displaying/altering information using an Internal Data Object in
the Report, the particular Data Object needs to be associated to the specific Interface
Object. E.g. If a particular ledger ‚ABC‛ is being altered in a Report, the Report will
be associated to the ledger Data Object ‚ABC‛
 Similarly if all the Data Objects of Ledger are displayed in Report, each line in the
Report will be associated with one specific Ledger Data Object

So, any expression will always have an Interface Object and the corresponding Data Object on
the basis of which it will be evaluated. Methods, Variables and Fields are Leaf components in
an expression as other components like Formulae or Functions finally evaluate into either one
of these or result into constants. A method value is evaluated based on the data object and
Variable and Field value is evaluated based on Interface object. The data type of the value
returned by an expression depends upon the data type of its operands. While evaluating the
expression the operator precedence is considered. If there is a data type mismatch, then
implicit conversion (type casting) will be handled by the language compiler.

114
Definitions, Attributes & Modifiers

We will now look into the default context fall through of the compiler for evaluation of various
components of an expression.
 Evaluating a method using $
Checks if it is an internal method or UDF

User defined Method

System Formula

Changes context to parent object in the hierarchy and the steps are repeated

 Evaluating a function using $$


Evaluation based on the requirements of the leaf components used as parameters

Evaluating a local formula using @

Evaluation based on the formula existing in the current Interface Object

 Evaluating a Global Formula using @@


 Evaluation of the formula based on the formula existing at the System Formula
level
 Evaluating a field value using #
 The evaluation will be based on the nearest field definition in the current inter-
face object hierarchy
 Evaluating a variable value using ##
  The evaluation will be based on the variable available in the current interface
object hierarchy and will be searched in the parent object hierarchy
Consider the following expression to understand the expression evaluation.

[System : Formula]
TDSITAssbleValue : $$ReportObject:$$CollectionFieldByKey:+
$AssessableAmount:@@TDSCategoryParty: +
TDSPartyCategoryColl

 First the value of the formula ‘TDSCategoryParty’ is evaluated


 The method ‘AssessableAmount’ value is retrieved from the collection
‘TDSCategoryParty’
 The function ‘CollectionfieldByKey’ is evaluated
 The function ‘ReportObject’ is executed for the value returned by the function ‘Col-
lectionfieldByKey’
 The value returned by the function Report Object is set for the formula
‘TDSITAssbleValue’.

115
Chapter 5: Dimensions, Formatting
and Report Layouts

5.1 Introduction
We have various definitions in TDL, which control the construction of the Interfaces. The
various visible elements on the Tally screen are Menu, Report, Button and Tables.
Report is the primary Interface element which is used for Display, Edit and Printing of data. In
order to create a Report, the other sub elements will be required which have a predefined con-
tainership and cannot exist on their own. They are Form, Part, Line and Field definitions. The
various specifications on Sizing, Alignment, Positioning and Formatting attributes applied for
these elements.
In this lesson, we will cover the various dimensional aspects of the screen design. The various
attributes, which control the appearance, will also be covered subsequently.

5.2 Unit of Measurement


Any physical quantity would require a unit of measurement for its measurement. In TDL the
measurements for the various Report elements are specified using the following UOM's:
 Millimeters/ mms
 Centimeters/ cms
 Inch(es)
 Number of Characters/ Number of Lines
 % Screen/ Page
 Number - Points (where 1 Point = 1/72 Inch)

It is advisable to follow the uniform unit of measurement throughout the Report


in order to avoid confusion.

117
Dimensions, Formatting & Report Layouts

5.3 Dimensional Attributes


Dimensional attributes can be classified into two types:
 Quantitative Attributes: These require specific measurements to be provided as
values
 Applicable Attributes: These attributes determine the applicability to the specific
definition on which it is specified. These take logical values
These attributes can be tabulated as below:
Definitions Quantitative Attributes Applicable Attributes
Form Height, Width, Space Top, Space Horizontal Align, Vertical
Bottom, Space Left, Space Right Align, Full Height, Full Width
Part Height, Width, Space Top, Space Horizontal Align
Bottom, Space Left, Space Right
Line Height, Space Top, Space Bot- Full Height
tom, Indent
Field Width, Space Left, Space Right, Full Width, Widespaced
Indent

5.3.1 Sizing/ Size Attributes


This category includes all attributes which help in specifying the size of the various elements
on the screen. All these sizing specifications are provided with respect to the overall screen/
paper size as reference.
Height and Width
Height attribute is used to specify the height required for the Form, Part and Line definition
whereas Width attribute is used to specify the width required for the Form, Part and Field Def-
inition.
Height and Width can be specified using any of the units of measurement. In the absence of
any measurement unit, Height attribute takes number of lines and Width attribute takes
number of characters as default UOM. The entire Height and Width is in the proportion of the
available paper/ screen dimensions.
Syntax
Height : <Measurement Formula>
Width : <Measurement Formula>
where,
<Measurement Formula> is used to specify the height or width in a specified unit of meas-
urement.

118
Dimensions, Formatting & Report Layouts

The following table shows the definitions and its supported attributes to be discussed in this
section.
Definition Attributes
Form Height, Width
Line Height
Field Width
Height and Width - Form Definition
Height and Width when specified in a Form Definition implies that it is the available Height
and Width, which can be utilized by all the Parts, Lines and Fields within the Form. If the
contents of the Part and Line exceed the available Height and/or Width, the contents of the
Form are squeezed to accommodate the same within the available Height and Width.
In the absence of any Height and Width specification, it assumes the Height and Width
required by the contents of the Form comprising of Parts, Lines and Fields.
Example:
[Form: Form Height Width]
Parts : Form Height Width
Height : 50% Page
Width : 50% Page

119
Dimensions, Formatting & Report Layouts

Height - Line Definition


Similarly, Height when specified within a Line definition restricts the contents of the Lines to
the available Line Height. Generally, specifying Line Height is not required as the contents of
the lines are controlled by the given Part Height.
Width - Field Definition
Width when specified within a Field definition limits the contents of the Field within the
defined boundary. If the contents are longer than the available Width, the Field contents are
squeezed to accommodate the same within the defined width.
FullHeight and FullWidth
The attribute FullHeight can be specified in a Form or a Line definition and the attribute
FullWidth can be specified in a Form or a Field definition. FullHeight is used to instruct the
Form or a Line to utilize the required Height. FullWidth is used to instruct the Form or a Field
to utilize the required Width.
Syntax
FullHeight: <Logical Value>
FullWidth : <Logical Value>
where,
<Logical Value> is to specify the logical value to the attribute
Example:
FullHeight: No
FullWidth : No
The following table shows the definitions and its supported attributes to be discussed in this
section.
Definition Attributes
Form FullHeight, FullWidth
Line FullHeight
Field FullWidth
FullHeight and FullWidth - Form Definition
FullHeight attribute decides whether to allow the form to consume the required Height or not
depending on the logical value set. By default, the value set to this attribute is Yes. If the
current Form uses Bottom Parts or Bottom Lines, then the Height required/ utilized by the
Form will be 100% Page/ Screen.
Similarly, FullWidth attribute decides whether to allow the form to consume the available Full
Width or not depending on the logical value set. By default, the value set to this attribute is
Yes. If the current Form uses Right Parts or Right Lines, then the Width required/ utilized by
the Form will be 100% Page/ Screen.

120
Dimensions, Formatting & Report Layouts

FullHeight - Line Definition


FullHeight attribute decides whether the line can consume the required Height or not
depending on the logical value set. By default, the value set to this attribute is Yes.
FullWidth - Field Definition
FullWidth attribute decides whether the Field can consume the required Width or not
depending on the logical value set. By default, the value set to this attribute is Yes.
Exercise 5.1
Objective
The objective of this program is to understand the dimensional attributes 'FullHeight' and
'FullWidth' and its implication on its usage along with Bottom Lines and Right Field
Capabilities Used
 The Form Attribute Fullwidth and FullHeight
 The Part Attribute Bottom Line and Line Attribute Right Field
 Switch Case usage and Optional Definitions
Code
[Report: Exer FullHeight and FullWidth]

Form : Exer FullHeight and FullWidth


Variable : Exer IsFullHeight, Exer IsFullWidth: Logical
Title : 'Dimensional Attributes FullHeight and FullWidth'

[Form: Exer FullHeight and FullWidth]

Parts : Form SubTitle, Exer FullHeight and FullWidth


Buttons : Exer Change FullHeight, Exer Change FullWidth
Local : Field: Form SubTitle: Info: "Understanding Dimensions+
FullHeight and FullWidth"
Switch: FullHeight: Exer FullHeight : ##ExerIsFullHeight
Switch: FullHeight: Exer NoFullHeight : NOT ##ExerIsFullHeight
Switch: FullWidth: Exer FullWidth : ##ExerIsFullWidth
Switch: FullWidth: Exer NoFullWidth: NOT ##ExerIsFullWidth
[!Form: Exer FullHeight]
/* The Form assumes the height required by its components Parts, Lines. If Bottom Parts or Lines are used, the Form
assumes its Height as 100% Page or Screen since by default,Form Height is enabled. On disabling the Form Attribute
'Full Height', it assumes only the required Form Height */

121
Dimensions, Formatting & Report Layouts

Full Height: Yes


Set As : “ABC”
[!Form: Exer No FullHeight]
Full Height: No
[!Form: Exer FullWidth]
/* The Form assumes the Width required by its component Parts, Fields. If Right Parts or Fields are used, the Form
assumes its Width as 100% Page or Screen since by default,Form Width is enabled. On disabling the Form Attribute 'Full
Width', it assumes only the required Form Width */
Full Width: Yes
[!Form: Exer No FullWidth]
Full Width: No
[Part: Exer FullHeight and FullWidth]
Lines : Exer Top Line
/* If, Form Attribute 'Full Height' is disabled, though Bottom Lines are used, the Form assumes only the required Height
by its UI components else it renders the Bottom Lines to the Bottom of the Page */
Bottom Lines: Exer Bottom Line
[Line: Exer Top Line]
Fields : Exer NormalWidth, Exer FullWidth
/* Since Field 'Exer Right Field' is used as a Right Field, this will be rendered in the rightmost corner of the Line if Form
FullWidth is enabled. If disabled, then only the required width will be utilized.*/
Right Fields: Exer Right Field

[Field: Exer NormalWidth]


Set As : "FullHeight of Form is enabled"
Background : Green
Border : Thin Box

[Field: Exer FullWidth]


Set As : "FullWidth is enabled in this Field"
/* Since FullWidth is enabled in this Field, Field assumes the Total available Width for the current Field. Ideally for Par-
ticulars Column Fields which contains data of varied width, FullWidth can be enabled */
Full Width : Yes
Background : Yellow
Border : Thin Box

122
Dimensions, Formatting & Report Layouts

[Field: Exer Right Field]


Set As : "This is the Right Field"
Background : White
Border : Thin Box

[Line: Exer Bottom Line]


Fields : Exer NormalWidth, Exer FullWidth
Right Fields: Exer Right Field
Local: Field: Default : Set As: "Same Fields in Bottom Line"

[Button: Exer Change FullHeight]


Key : Alt + H
Action : Set : Exer Is FullHeight: NOT ##ExerIsFullHeight
Title : If ##ExerIsFullHeight then "No FullHeight" else +
"FullHeight"

[Button: Exer Change FullWidth]

Key : Alt + W
Action : Set : Exer Is FullWidth: NOT ##ExerIsFullWidth
Title : If ##ExerIsFullWidth then "No FullWidth" else "FullWidth"
;; End-of-File

Output

Figure 1.1 Understanding Dimensions FullHeight and Fullwidth (a)

123
Dimensions, Formatting & Report Layouts

Figure 1.2 Understanding Dimensions FullHeight and Fullwidth (b)

Program Explanation
The above program is used to explain the usage and implications of the form attributes Full-
Height and FullWidth. The report shows the usage of FullHeight and FullWidth attribute by
using the buttons FullHeight and FullWidth. These two buttons are available to toggle the
values of variable and depends on the value of these variables the output is shown as above.
The form Exer FullHeight and FullWidth defines four switch conditions, it further defines
the optional forms to set the value of FullHeight, and FullWidth attributes. The Part Exer Full-
Height and FullWidth define the Lines and Bottom Lines for the part and the values are
displayed in the fields called Exer NormalWidth, Exer FullWidth and Exer Right Field.
The width of these fields is varied based on the Logical variable value from the switch condi-
tions. Based on the value of satisfied condition, the relevant optional form is get evaluated.
Similarly, the button title is altered based on the variable value.

FullScreen
The attribute FullScreen is used in Report definition. It helps to control the display of
command window/calculator pane. It is a logical type of attribute.

124
Dimensions, Formatting & Report Layouts

Syntax
FullScreen : <Logical Value>
The attribute Full Screen is set to Yes, command window will be hidden providing extra space
to the report displayed. The default value of this attribute is Yes. In case of the SubReport/
AutoReport, if the value of this attribute is not specified, the default value is No.
Example:
[Report: Attr FullScreen]
Full Screen : Yes
5.3.2 Spacing/ Position Attributes
This category includes all attributes, which help in specifying the space to be provided for the
various elements on the screen.

Space Top, Space Bottom, Space Left and Space Right


Attributes Space Top, Space Bottom, Space Left and Space Right are used to specify the
spaces to be kept to the Top, Bottom, Left and Right of the definition. Space Top and Space
Bottom can be used in a Form, Part and Line definition. Space Left and Space Right can be
used in a Form, Part and Field definition. When Space Top, Space Bottom, Space Left and
Space Right are used in a definition, these spaces are included in the Height and Width speci-
fication within the definition.
Syntax
Space Top : <Measurement Formula>
Space Bottom : <Measurement Formula>
Space Left : <Measurement Formula>
Space Right : <Measurement Formula>
Example:
[Part: Spacing Attribute Part]
Lines : SA Line
Space Top : 5
Space Bottom : 3
Space Left : 5
Space Right : 3

125
Dimensions, Formatting & Report Layouts

The output of these spacing attributes as shown below:

The following table shows the definitions and its supported attributes to be discussed in this
section.
Definition Attribute
Line Space Top, Space Bottom
Field Space Left, Space Right

Space Top, Space Bottom, Space Left and Space Right - Form/ Part Definition
Space Top, Space Bottom, Space Left and Space Right when specified in Form or a Part defi-
nition leave the appropriate spaces before displaying/printing a Form. These spaces are
included in the Height/ Width of the Form definition.
Space Top and Space Bottom - Line Definition
Space Top and Space Bottom when specified in a Line definition leave the appropriate spaces
before/ after the Line. These spaces are inclusive within the Height of the specific Part in
which the current Line definition resides. If the Height of the Part is unable to accommodate
the same, it compresses the line to fit it within the available Height.
Space Left and Space Right - Field Definition
Space Left and Space Right when specified in a Field definition leave the appropriate spaces
before/ after the Field. These spaces are inclusive within the Width of the Part and Field. If the
Width of the Part is unable to accommodate the same, it compresses the Fields within the Parts
and Lines to fit it within the available Width.

Indent
Indent can be specified in either a Line or a Field definition. It is similar to the Tab Key,
which is used to specify a starting point for a Line or a Field.

126
Dimensions, Formatting & Report Layouts

Syntax
Indent: <Measurement Formula>
Example:
[Line: Indent Line]
Fields : Indent Field1, Indent Field2

[Field: Indent Field1]


Info : "This is Field1"
Width : 30 mms

[Field: Indent Field2]


Info : "This Field is indented by 2 mms"
Width : 45 mms
Indent : 2 mms
The field Indent Field2 will be indented by 2 mms. The output for the same is as shown
below:

Indent - Line Definition


This attribute in Line definition specifies the space to be left from the Left margin before the
contents of the line begin.
Indent - Field Definition
This attribute in Field definition acts the same as Space Left attribute, except that this attribute
indents the field independent of width of the field. Space Left indents the field within the
width available. However, Indent indents the field exclusive of the width. It can take a formula
as a parameter or we can give the expression itself as parameter. The formula can decide as to
what extent each instance of the field has to be indented from the initial place. This attribute is
typically used while displaying reports like list of accounts, Trial Balance, etc where the
groups and ledgers under a particular group are recursively indented inside the group, based on
the order of the groups and ledgers.

127
Dimensions, Formatting & Report Layouts

Exercise 5.2
Objective
The objective of this TDL is to understand the applicability of Sizing ad Spacing attributes.
Capabilities Used
 The Line attributes Space Bottom, Space Top and Right Fields
 The Part attribute Lines
 The Field attributes Space Left, Space Right and Indent
Code
[Report: Exer SizingSpacing Attributes]
Form : Exer SizingSpacing Attributes
Title: "Sizing and Spacing Attributes"

[Form: Exer SizingSpacing Attributes]


Parts : Form SubTitle, Exer SS Attributes
Local : Field: Form SubTitle: Info:"Understanding Sizing +
and Spacing Attributes"
[Part: Exer SS Attributes]
Lines : Exer SS Line1, Exer SS Line2

[Line: Exer SS Line1]


Fields : Exer SS Field1, Exer SS Field2
Right Fields: Exer SS Field3

[Field: Exer SS Field1]


Set As : "Field Space Left as 50 mms "
/* Before rendering this Field, 50 mms of Space from the Left will be left. Space Left in mms will be included in the Width
of the Field */
Space Left : 50 mms
;; After leaving the Space Left i.e., 50 mms, the balance of 30 mms will be utilized for this Field.
Width : 80 mms
Background : Green
Border : Thin Box

128
Dimensions, Formatting & Report Layouts

[Field: Exer SS Field2]


Set As : "Field indented by 10 mms"
;; Indent of 10 mms is left prior to rendering this Field.
Indent : 10 mms
Background: Yellow
Border : Thin Box

[Field: Exer SS Field3]


Set As : "Right Field with Space Right as 10 mms"
/*Before rendering this Field, 25 mms of Space from the Right will be left. Space Right in mms will be included in the
Width of the Field.*/
Space Right : 25 mms
Background : White
Border : Thin Box

[Line: Exer SS Line2]


Fields : Exer SS Field1, Exer SS Field2
Right Fields: Exer SS Field3
;; End-of-File
Output

129
Dimensions, Formatting & Report Layouts

Program Explanation
The report shows the usage and implication of sizing and spacing attributes. The Line 'Exer
SS Line1' is displayed after 25 mms of Space from the Top. After this Line 70 Mms of Space
is left from the Bottom by using the attribute Space Bottom before displaying the next Line or
part.
The Field Exer SSField1 is displayed after leaving 50 mms of space from the left. From the
program it is understood the width of this field is 80mms and this includes both space left
value and actual width of the field ie., 50mms is used for space Left and the balance 30mms is
assigned as actual field width.
The Field Exer SSField2 is displayed after leaving 10mms from the left ie., the field is
indented by 10mms.
The Field Exer SSField3 is displayed after leaving 25mms of space from the right by using
Space Right attribute and the width of this field is includes this 25mms also.
The attribute Background is used to give different background colors for the fields, Exer
SSField1, Exer SSField2 and Exer SSField3. Similarly Border attribute is used to border for
each fields.
5.3.3 Alignment Attributes
This category includes all attributes, which help in specifying the alignment of various
elements on the screen.

Top Parts, Bottom Parts, Left Parts and Right Parts


These attributes are used to place different parts at different positions in a particular Form or
Part. Attributes Top Parts and Bottom Parts can be specified both in Form as well as Part Def-
inition whereas attributes Top Parts, Bottom Parts, Left Parts and Right Parts can be specified
in a Part Definition.
Syntax
Top Parts : <Part1, Part2, ….>
Bottom Parts : <Part1, Part2, ….>
;; For both Form and part definitions
Left Parts : <Part1, Part2, ….>
;; Only for Part Definition
Right Parts : <Part1, Part2, ….>
;; Only for Part Definition

Example:
[Form: Top and Bottom Parts]
Top Parts : TBTopPart
Bottom Parts: TBBottomPart

130
Dimensions, Formatting & Report Layouts

[Part: TBTopPart]
;; Only for Part Definition
Left Parts : TB Left Part
Right Parts : TB Right Part
The following table shows the definitions and its supported attributes to be discussed in this
section.
Definition Attribute
Form Top Parts, Bottom Parts
Part Top Parts, Bottom Parts, Left Parts, Right Parts

Top Parts and Bottom Parts – Form Definition


If Top Part or Bottom Part is specified within a Form definition, it occupies the Top Section or
Bottom Section of the Form respectively keeping Space Top and Space Bottom of the Form in
account. Space Bottom impacts the Bottom Parts by moving it from bottom in order to leave
appropriate spaces. Similarly, Space top impacts the Top Parts by moving it from top in order
to leave appropriate spaces.

The Bottom Parts/ Bottom Lines start printing from bottom to the top of the Form. If Height is
specified at the Form Definition, then the Bottom Parts/ Lines start printing from the bottom-
most line within the specified Height.
Exercise 5.3
Consider the following code Snippet. The objective is to understand the Top and Bottom
attributes at Form. Top and Bottom parts render the parts at the Top and Bottom respectively
within the available Form Height
[Form: Exer Top and Bottom Parts Form]
;; Top Parts are rendered at the Top of the Form after excluding the Space to leave at Top
Top Parts : Form SubTitle, Exer TB PF Top
;; Bottom Parts are rendered at the Bottom of the Form based on the available Form Height after excluding the Space to leave at
Bottom
Bottom Parts: Exer TB PF Bottom
Local: Field: Form SubTitle: Info: "Understanding Top and Bottom+
Part Attributes - Form"
/* The following are Form Dimensions i.e., Height, Width of the Form and Space Top and Bottom to be left. Space Top and
Bottom are also included within the Height and Width of the Form.*/
Height : 50% Page
Width : 50% Page
Space Top : 0.25 inch

131
Dimensions, Formatting & Report Layouts

Space Bottom : 0.5 inch


The output for the above code is as shown below:

The above output demonstrates the usage of Top parts and Bottom parts under Form defini-
tion. The Top Part Exer TB PF Top is given at the Top of the Form after excluding the Space
to leave at Top. Bottom Parts Exer TB PF Bottom are displayed at the Bottom of the Form
based on the available Form Height after excluding the Space to leave at Bottom.
For the entire TDL code of the given example, please refer Exercises 5.3

Top Parts, Bottom Parts, Left Parts and Right Parts – Part Definition
In cases where the Left Part or Right Part is specified within a Part Definition, it occupies the
left section or right section of the Part respectively keeping Space Left and Space Right of the
Part in account. Space Right impacts the Right Parts by moving it from right in order to leave
appropriate spaces. Similarly, Space Left impacts the Left Parts by moving it from Left in
order to leave appropriate spaces.
If the intent is to have multiple parts printed horizontally, then the Part attribute Vertical should
be set to No. If Vertical Attribute is set to Yes, then all the parts within this part will be printed
vertically. In such circumstances, the Left Parts will position at the Top of the Screen/ Page
and Right Parts will position at the Bottom of the Screen/ Page.
Incases where the Top Part or Bottom Part is specified within a Part definition, it occupies the
top section or bottom section of the Part respectively keeping Space Top and Space Bottom of
the Part in account. Space Bottom impacts the Bottom Parts by moving it from bottom in
order to leave appropriate spaces. Similarly, Space Top impacts the Top Parts by moving it
from Top in order to leave appropriate spaces.
If the intent is to have multiple parts printed vertically, then the Part attribute Vertical should
be set to Yes. If Vertical attribute is set to No, then all the parts within this part will be printed

132
Dimensions, Formatting & Report Layouts

horizontally. In such circumstances, the Top Parts will position at the Left of the Screen/ Page
and Bottom Parts will position at the Right of the Screen/ Page.
Exercise 5.4
[Part: Exer Parts Part]
/* Parts can be rendered either vertically or horizontally. In this case, Parts are rendered horizontally as the Part Attribute 'Ver-
tical' is not enabled/*
Parts : Exer Parts PartL
Right Parts : Exer Parts PartR
Height : 50% Page
Border : Thin Top Bottom

[Part: Exer Parts PartL]


Top Parts : Exer Parts PartLT
Bottom Parts : Exer Parts PartLB
/*Since the Attribute Vertical is enabled here, both the Parts are rendered vertically i.e., one below the another. Bottom Parts will
be rendered at the Bottom of the current part 'Exer Parts PartL'*/
Vertical : Yes
Width : 75% Page
The output for the above code is as shown below:

Program Explanation
In the above output, the attribute Top Part displays the top part of a part and the attribute Right
part shows the Right Part of a part. Ie., Exer Parts Part has further two more parts as one
Left part and one Right part called Exer Parts PartL and Exer Parts PartR. The Left part
Exer Parts PartL divided into two parts called the top part Exer Parts PartLT and the

133
Dimensions, Formatting & Report Layouts

bottom part Exer Parts PartLB and the attribute vertical is used set the parts vertically, ie.,
one below another.
For the entire TDL code of the given example, please refer Exercises 5.4

Both Parts and Lines are not allowed within a Part. They are mutually
exclusive entities. Either Parts or Lines can be used.

Top Lines and Bottom Lines


These attributes are used to place different lines at different positions in a particular Part Defi-
nition. Attributes Top Lines and Bottom Lines can be specified in Part Definition. Top Lines/
Lines can only be used in Line and Field Definition.
Syntax
Top Lines : <Line1, Line2,…..>
Bottom Lines : <Line1, Line2,…..>
Example:
[Part: TBL Part]
Top Lines : TBL Part Top Line
Bottom Lines: TBL Part Bottom Line
The following table shows the definitions and its supported attributes to be discussed in this
section.
Definition Attribute
Part Top Lines, Bottom Lines
Line Top Lines/Lines
Field Lines

Top Lines and Bottom Lines – Part Definition


Attribute Top Lines is used to place lines at the top and the attribute Bottom Lines are used to
place the lines at the bottom of the part with respect to the Height specified within the Part
Definition.

Exercise 5.5
Consider the following example to demonstrate the attribute Top Lines and Bottom Lines.

134
Dimensions, Formatting & Report Layouts

[Part: Exer TBL Part]


;; Top and Bottom lines render the lines at the Top and Bottom respectively within the current Part
Top Lines : Exer TBL Part Top Line
Bottom Lines : Exer TBL Part Bottom Line
Horizontal Align: Center
The output for the above code is as shown below:

For the entire TDL code for the above snippet, please refer Exercises 5.5
Top Lines/ Lines – Line Definition
The attribute Top Line/Line is used in a Line definition to define another line inside one.
These attributes are also useful if more than one line needs to be repeated over a collection.

Part attributes, Repeat and Collection are advanced topics and will be
discussed later in the section, Objects, Methods and Collections.

Lines – Field Definition


Attribute Lines is used in a Field definition to wrap the contents of the Field to the subsequent
line. Here the number indicates the Number of Lines to be wrapped. It also accepts 0 as its
value which means depending on the requirement of Lines, it wraps the contents accordingly.
If the content is more than the specified space then the behaviour is different in display and
Print. In display it shows only what is possible but the user will be allowed to scroll. In case of
Print remaining text will be fitted in last line.

135
Dimensions, Formatting & Report Layouts

Syntax
Lines : <Numerical Value>
Where,
<Numerical Value> is any number

Example:
Lines : 2
Exercise 5.6
Consider the following example to demonstrate the usage of lines attribute under field defini-
tion
[Field: Exer LWF]
Set as : "By default, the Lines is set as 1 in the Default Field,
we can override the same to set another number. If any other
number is set, the contents can be split into the fixed number of
lines specified. But if 0 is set, it can be split to as many lines
as required and available within the current Part. If Lines is
specified as 0, Width is mandatory."
Background: Green
/* By default, the Lines is set as 1 in the Default Field, we can override the same to set another number. If any other number is set,
the contents can be split into the fixed number of lines specified. But if 0 is set, it can be split to as many lines as required and
available within the current Part. If Lines is specified as 0, Width is mandatory.*/
Lines : 0
ToolTip : "Lines is set to 0 (Zero) in this Field"
Width : 50% Page

[Line: Exer LWF Line2]

Fields: Exer LWF


Local : Field: Exer LWF: Lines: 3
Local : Field: Exer LWF: Background : Yellow
Local : Field: Exer LWF: ToolTip: "Lines is set to 3 (Three) in+
this Field"
SpaceTop: 1

136
Dimensions, Formatting & Report Layouts

For the entire TDL code of above snippet, please refer Exercises 5.6
Left Field and Right Field
Attribute Left Fields can be specified in both Line and Field definition whereas attribute Right
Fields can only be specified in a Line Definition.
Syntax
Left Fields : <Field1, Field2, ….>
Right Fields : <Field1, Field2, ….>
Example:
Left Fields : Medium Prompt, Chg SVDate, Chg VchDate
Right Fields: Trader TypeofPurchase, Trader QtyUtilisedTotal

Definition Attribute
Line Left Fields, Right Fields
Field Left Fields/Fields

Left Fields and Right Fields – Line Definition


The attribute Left Fields and Right Fields specified in a Line definition places the fields at
their respective position. While printing the attribute Left Fields starts printing from the Left
to Right of the Line whereas the Right Fields starts printing from the Right to Left of the Line.
If Repeat attribute is used in a Line, specification of Right Fields are not allowed as by default,
Repeat attribute places the Field specified to the Right of the Screen/Page.

137
Dimensions, Formatting & Report Layouts

Exercise 5.7
Consider the following code snippet to understand the usage of Left and Right Fields.

[Line: Exer FWL Line1]


;; Right Fields move the Fields and start rendering the same from the extreme right.
Fields : Exer FWL Field1
Right Fields: Exer FWL Field2
The output of this code shows as below:

The Right field values move the fields and start rendering the same from the extreme right.
For the entire TDL code for the above snippet, please refer Exercises 5.7

Left Fields / Fields – Field Definition


The attribute Field is used to create fields containing one or more fields, like Group fields. We
can create multiple fields inside a single field using the Fields attribute. The attribute Fields is
useful when multiple Fields are required to be repeated in a Line.
For example, in case of a Trial Balance, two Fields i.e., Debits and Credits are required to be
repeated together if a new column is added by a user. The new column thus added, should
again contain both these fields, i.e., Debit and Credit. In a Line definition, only one Field can
be repeated. So, a Field is required within a Field if more than one field requires to be
repeated.

Align
The attribute Align aligns the contents of a Field as specified. The permissible values to this
attribute are Left, Center, Right, Justified and Prompt.

Syntax
Align : <String Value>
Example:
Align : Right

138
Dimensions, Formatting & Report Layouts

Horizontal Align and Vertical Align


Horizontal Align sets the alignment of the Form or Part horizontally and Vertical Align sets
the alignment of the Form vertically.
Syntax
Horizontal Align : <Left, Right, Centre>
;; Only for Form Definition
Vertical Align : <Top, Bottom, Centre>
Example:
Horizontal Align: Right
;; Only for Form Definition
Vertical Align : Bottom
The alignment of the Form or Part across the width of the page is set by the attribute Horizon-
tal Align. The default alignment of the Form and Part is Centre on screen and Left on print.
Depending on the width of the Form and Page, the Form or Part will be displayed / printed
leaving equal amount of space on the left and right of the Form.
The alignment of the Form across the height of the page is set by the attribute Vertical Align.
The default alignment of the Form is Centre on screen and Top on print. Depending on the
height of the form and page, the form will be displayed / printed leaving equal amount of
space on the top and bottom of the form.

Scroll Flow/Vertical /Both


Scroll attribute is used to display the informations in the Report, in the allotted height and the
user can navigate to the remaining data using the cursor in display mode. When a TDL report
is designed without the use of scroll attribute the system will try to arrange the complete data
in a single page or same screen. Scroll attribute is used in Part or Field.
In the part definition, the value of this attribute is Flow/Vertical/Both.
Syntax
Scroll: Flow/Vertical/Both
The attribute value Flow enables the arrangement of information display one after another as
defined the TDL program
The attribute value Vertical is used, when there are two vertical sub-parts inside a main part.
‘Scroll: Vertical’ is applied at the sub-part level and both the sub parts are repeated over
different set of information which may run into multiple pages. It starts printing both the sub
parts from the first page itself (partially) and it continues the remaining part in the next page.
The attribute value Both is used when all the fields are get compressed if we display a report
having more number of fields. The user can make use of Part Attribute Scroll with value as
Both in which the Lines and Fields get repeated. By using this attribute the part will be

139
Dimensions, Formatting & Report Layouts

displayed clearly and can be scrolled both, across the Fields Horizontally as well as Lines Ver-
tically.
Difference between Scroll: Vertical and Scroll: Flow is as follows:
Scroll : Vertical Scroll : Flow
When there are two vertical sub-parts In similar scenario, if we apply
inside a main part with “Scroll : Vertical” “Scroll : Flow” at the main part, and
applied at the sub-part level and both the “Scroll : Vertical” at the sub part, it
sub parts are repeated over different set of completes the first sub-part
information which may run into multiple (whether single or multiple pages)
pages, it starts printing both the sub parts then starts printing the subsequent
from the first page itself (partially) and it sub-part
continues the remaining part in the next
page.
Again, if we apply “Scroll: Vertical” at However if the sub-part is further
the main part itself, then it prints the sub divided into two or more horizontal
parts one after another. sub-parts, it prints all the sub-parts
vertically ONLY. This happens
because once a Part is defined with
“Scroll: Vertical”, all the sub-parts
and child parts will be treated as
Vertical Parts. Where as if we apply
“Scroll: Flow” at the main part, we
can have a combination of vertical
and horizontal sub parts.
Exercise 5.8
Objective
The objective of this program is to understand the applicability of various alignment attributes.
Capabilities used
 Form attributes Space Top, Space Bottom, Space Left, Space Right
 Form attribute Height, Width
 Part attributes Lines, Bottom Lines, Border and Vertical
 Line attributes Fields, Right Fields

140
Dimensions, Formatting & Report Layouts

Code
[Report: Exer Alignment Attributes]
Form : Exer Alignment Attributes
Title : "Alignment Attributes"
[Form: Exer Alignment Attributes]

Parts : Form SubTitle, Exer Alignment Attributes


Local : Field: Form SubTitle: Info: "Working with various Alignment+
Attributes"
Height : 100% Screen
Width : 100% Screen
Space Left : 5% Screen
Space Right : 5% Screen
Space Top : 5% Screen
Space Bottom: 5% Screen

[Part: Exer Alignment Attributes]


Parts : Exer Alignment Attributes TPart
;; Bottom Parts start rendering the part from the Bottom of the Part 'Exer Alignment Attributes'.
Bottom Parts : Exer Alignment Attributes BPart
Border : Thin Box
Vertical : Yes

[Part: Exer Alignment Attributes TPart]


Lines : Exer AAP TLine1, Exer AAP TLine2
;; Bottom Lines start rendering the line from the Bottom of the Part 'Exer Alignment Attributes TPart'.
Bottom Lines : Exer AAP BLine1
Height : 25% Screen

[Line: Exer AAP TLine1]


Fields : Exer AAP LField
;; Right Fields start rendering the field from the Right of the Line 'Exer AAP TLine1'.
Right Fields : Exer AAP RField

141
Dimensions, Formatting & Report Layouts

Space Top : 5% Screen


Border : Thin Bottom

[Field: Exer AAP LField]


Set As : "Top Part - Top Line - Left Field"

[Field: Exer AAP RField]


Set As : "Top Part - Top Line - Right Field"
Space Right : 5% Screen

[Line: Exer AAP TLine2]


Fields : Exer AAP LField
Right Fields: Exer AAP RField
Border : Thin Bottom
Local: Field: Exer AAP LField: Set As: "Top Part - +
Middle Line - Left Field"
Local: Field: Exer AAP RField: Set As: "Top Part - +
Middle Line - Right Field"
[Line: Exer AAP BLine1]
Fields : Exer AAP LField
Right Fields: Exer AAP RField
Space Bottom: 5% Screen
Local: Field: Exer AAP LField: Set As: "Top Part -+
Bottom Line - Left Field"
Local: Field: Exer AAP RField: Set As: "Top Part -+
Bottom Line - Right Field"

142
Dimensions, Formatting & Report Layouts

[Part: Exer Alignment Attributes BPart]

Use : Exer Alignment Attributes TPart


Local : Line : Exer AAP TLine1: Local: Field: Exer AAP LField:+
Set As: "Bottom Part - Top Line - Left Field"
Local : Line : Exer AAP TLine1: Local: Field: Exer AAP RField: +
Set As: "Bottom Part - Top Line - Right Field"
Local : Line : Exer AAP TLine2: Local: Field: Exer AAP LField: +
Set As: "Bottom Part - Middle Line - Left Field"
Local : Line : Exer AAP TLine2: Local: Field: Exer AAP RField: +
Set As: "Bottom Part - Middle Line - Right Field"
Local : Line : Exer AAP BLine1: Local: Field: Exer AAP LField: +
Set As: "Bottom Part - Bottom Line - Left Field"
Local : Line : Exer AAP BLine1: Local: Field: Exer AAP RField: +
Set As: "Bottom Part - Bottom Line - Right Field"
Background : Yellow
Border : Thin Top
;;End-of-File

143
Dimensions, Formatting & Report Layouts

Output

Program Explanation
The report is displayed by using various alignment attributes. The Form Exer Alignment
Attributes is displayed 100% Screen by using the form attributes Height and width. The four
sides of form are left with 5% screen space by using the space attributes like Space Left, Space
Right, Space Top and Space Bottom.
The part Exer Alignment Attributes contains two parts Exer Alignment Attributes TPart
and Exer Alignment Attributes BPart. The top part is rendered at the top of the main part
and the bottom part is rendered at the bottom. Similarly, these two parts includes three
different lines ie., two top lines and one bottom line. This bottom line Exer AAP BLine1
displayed at the bottom of the part Exer Alignment Attributes TPart.
The Line Exer AAP TLine1 contains two fields called Exer AAP LField and Exer AAP
RField. The Right field Exer AAP RField start displaying from the right of the line Exer
AAP TLine1.
The attribute Background is used to give background color to the two parts Exer Alignment
Attributes TPart and Exer Alignment Attributes BPart.

144
Dimensions, Formatting & Report Layouts

5.3.4 Some Specific Attributes


Inactive
The Inactive attribute can be used in both Field and Button definition. When the attribute
Inactive is set to Yes in a Field Definition, the space for the field will be retained without the
Field contents. In cases where a Button definition is used, the button becomes Inactive.
Syntax
Inactive: Logical Formula
Example:
[Field: TBCrAmount]
Set as : $ClosingBalance
Inactive : $$IsDr: $ClosingBalance
In the above example, the Field TBCrAmount is used to display the credit amount of the
Ledger in a Trial Balance. When the Ledger balance is debit, the amount should not be
displayed in the credit column but the width should be utilized to avoid the debit field being
shifted to the credit field. The credit totals to be calculated and displayed will also exclude the
Debit Amount.

Invisible
The attribute Invisible can be specified in Part, Line or Field definition. Based on the logical
condition, this attribute decides whether the contents of the definition should be displayed or
not. When this attribute is set to Yes, it does not display the contents but the contents are
retained for further processing. In this case, contrary to Inactive, the size of the entire field is
reduced to null but the value is retained.
Syntax
Invisible: Logical Formula

Invisible – Field Definition


The invisible attribute when specified in a Field denotes that the current field is excluded from
all the further processing based on satisfying certain condition.
Example:
[Field: Attr Invisible]
Set as : “Invisible Attribute”
Invisible : Yes

In the above example, this field Attr Invisible does not display the string Invisible Attribute
because the value of the attribute is Yes. If the value of the attribute is No then it displays the
string.

145
Dimensions, Formatting & Report Layouts

Exercise 5.9
Consider the following the code snippet:
[Line: Exer IAI Details]
Fields : Medium Prompt, Simple Field
RightFields : Name Field
Local : Field : Medium Prompt: Set as: "Company Address"
Local : Field : Medium Prompt: Style: Normal Bold
;; Here, the prompt is made Inactive beyond first line, as a result of which the space will be retained without the Field contents
Local : Field : Medium Prompt: Inactive: $$Line > 1
;; Function Line returns the current Line Number in a repeated Environment
Local : Field : Simple Field: Set as: $Address
Local : Field : Simple Field: FullWidth: Yes
/* Value of Field 'Medium Prompt' is set to the Field 'Name Field'. Second Line onwards, the value of the Field 'Medium Prompt'
will be empty due to Field Attribute 'Inactive'. With Field Attribute 'Invisible', the contents of the Field 'Medium Prompt' will be
available as seen in the Part 'Exer IAI Part Invisible'*/
Local : Field : Name Field: Set as: #MediumPrompt
Local : Field : Name Field: Background: Green
Local : Field : Name Field: Style: Normal Italic
Local : Field : Name Field: Width: @@MediumWidth

[Part: Exer IAI Part Invisible]


Use : Exer IAI Part Inactive
Local : Field: Exer IAI Title :Info: "Field Attribute 'Invisible'"
Local : Line : Exer IAI Details : Local : Field : Medium Prompt: +
Inactive: No
/* Here, the prompt is made Invisible beyond first line, as a result of which the Field will not occupy any width but the Field
contents will be available*/
Local : Line: Exer IAI Details: Local: Field : Medium Prompt+
:Invisible: $$Line > 1
Local : Line: Exer IAI Details: Local: Field: Name Field : +
Background: Yellow
Border: Thin Left

146
Dimensions, Formatting & Report Layouts

Output

The above report demonstrates the usage of Inactive and Invisible attributes. Inside the line
Exer IAI Details, the field medium prompt set the value as “Company Address” and further
the field is made Inactive, if $$Line>1then from second line onwards space for the field will
be retained without the field content. Here the field medium prompt is displayed in green
background.
Similarly, in the Part Exer IAI Part Invisible, the field Medium Prompt made Invisible, the
contents of the field Medium prompt is available and displayed, but it did not occupy any
width, ie., Here the field medium prompt is displayed in Yellow background. Function $$Line
returns the current line number.
For the entire TDL code for the above snippet, please refer Exercises 5.9.

In a Report, at least one Part, Line and Field should be visible.

Fixed
The attribute Fixed can be specified in Part, Line and Field. In part definition when the
attribute Fixed is set to yes, it forces the cursor to skip the Part. In the alteration screen it
allows the TDL programmer to skip a part of a Form which is not meant to be altered. In Line
definition it skips the line such that the cursor will not positioned on it. The attribute Fixed
when used in a field definition does not allow the user to change the value of the field.
Syntax
Fixed : < Logical Value >
Example:
Fixed: Yes
Widespaced
This attribute is used in Field definition which allows increased spacing between the charac-
ters of the string value specified in the field. This attribute is used to create titles for the report
/ columns.

147
Dimensions, Formatting & Report Layouts

Syntax
Widespaced: Logical Value
Example:
Widespaced: Yes

Preprinted
This attribute can be used in Part, Line or a Field definition. When this attribute is set to Yes,
the contents of the current definition will not be printed assuming that they have been pre-
printed. Ideally, Preprinted is used where static texts are assumed to be preprinted like Invoice
printing, where Company Name, Address, static declaration, etc. are preprinted.
Syntax
Preprinted: Logical Value
Example:

Preprinted: Yes
SubTitle
This attribute can be used in Field definition as well as Collection definition. In the Field def-
inition, if the value of SubTitle is set to Yes, the current field will be considered as a subtitle
and the border will not be extended to the current field.
For example, in a Trial Balance Report where Column headings are displayed, first line dis-
playing Closing Balance and the second line displays two fields consisting of Debit and Credit
fields below the Closing Balance. Now the Common Border at the Part definition will extend
the Border between the Debit and Credit to the Closing Balance Line too. This will be
prevented by saying SubTitle : Yes in the Closing Balance Field.
Syntax
SubTitle: Logical Value
Example:
[Field : SubTitle Field]
SubTitle: Yes

In Collection definition, this attribute gives the Subtitles for each column in the table.
Syntax
SubTitle: List of Column Titles
where,
<List of Column Titles> specifies the Title for the columns

148
Dimensions, Formatting & Report Layouts

5.4 Definitions and Attributes for Formatting


5.4.1 Border
The definition Border determines the type of lines required in a border which can be used by a
Part, Line or a Field which means that this definition can define customized borders for the
user. But it is ideal to use the predefined borders which are part of the default TDL instead of
user defined, since almost all possible border combinations are already defined in the Default
TDL.
Syntax
[Border: <Border Name>]
Top : <Values separated by a comma>
Bottom : <Values separated by a comma>
Left : <Values separated by a comma>
Right : <Values separated by a comma>
Color/Shade : <Color Name – B&W, Color Name - Color>
PrintFG : <Color Name>

Top, Bottom, Left and Right


Top, Bottom, Left and Right attributes in Border definition are used to add appropriate lines
which constitute the Border defined. The permissible values for these attributes are:
 Thin/Thick : This specifies whether the Line should be thin or thick
 Flush : Border includes the spaces on the Top, Bottom, Left or Right
 Full Length : This ignores the space given at the Top, Bottom, Left or Right and
prints the border for the whole length
 Double : This parameter forces double line to be printed. In its absence, it is
assumed to be single line
Example:
[Border: Thin Bottom Right Double]
Bottom : Thin, Flush, Full Length
Right : Thin, Double

[Field: Total Field]


Set As : $Total
Border : Thin Bottom Right Double

149
Dimensions, Formatting & Report Layouts

Color / Shade
Color or Shade attribute of Border definition is useful to specify the color required for the
border while in display mode. Border attribute Color requires two values to be specified, viz.,
one which is used in case of a Black and White Monitor and second in case of a color monitor.
Example:
[Border: Top Bottom Colored]
Top : Thin
Bottom : Thin
Color : "Deep Grey, LeafGreen"
[Field: Total Field]
Set As : $Total
Border : Top Bottom Colored

PrintFG
PrintFG attribute of Border definition is useful to specify the color required for the border
during printing.
Example:

[Border: Top Bottom Colored]


Top : Thin
Bottom : Thin
Color : "Deep Grey, Leaf Green"
Print FG : “Leaf Green”

[Field: Total Field]


Set As : $Total
Border : Top Bottom Colored

Style
Style definition determines the appearance of the text being displayed/printed by using a cor-
responding font scheme, Bold, Italic, Point Size, Font Name, etc. This definition Style can be
used in the Field definition only.
Style attribute in Field definition is used to format the appearance of the text appearing within
the Field both in display and print mode provided the Print Style attribute is not used within

150
Dimensions, Formatting & Report Layouts

the current Field. Print Style attribute in Field is used if the Style specified while displaying is
different from the Style required while printing.

Syntax
[Style: <Style Name>]
Font : <Font Name>
Height : <required Font Height in Point Size>
Bold : <Logical Formula>
Italic : <Logical Formula>
Where,
<Style name> is the name of the style definition
<Font Name> is the name of the Name of the Font

Font
This is the generic name of the Font supported by the Operating System. Font is system
dependent and we do not have any control over them. However, one can select the required
fonts from among the available fonts.

Example:
[Style: Normal]
Font : If $$IsWindows then "Arial" else "Helvetica"
Height : @@NormalSize

[Style: Normal Bold]


Use : Normal
Bold : Yes

[Field: Party Name]


Set As : $PartyLedgerName
Style : Normal
Print Style : Normal Bold

151
Dimensions, Formatting & Report Layouts

Height
Height attribute within the Style definition should be specified without any measurement spec-
ification as it is always measured in terms of Points. The value for the attribute Height can
have fractions and can be denoted by a formula which returns a number.

One can also grow or shrink the Height by a multiplication factor or percentage.
Example:
[Style: Normal Large]
Use : Normal
Height : 25%

Bold
The attribute Bold can take only logical value/ formula. In other words, it can take either Yes
or No. This signifies that the Field using this Style should be printed in Bold.

Example:
[Style: Normal Bold Large]
Use : Normal Large
Bold : Yes
Italic
The attribute Italic can take only logical value/ formula. In other words, it can take either Yes
or No. This signifies that the Field using this Style should be printed in Italics.

Example:
[Style: Normal Large Italics]
Use : Normal Large
Italic : Yes

Color
The definition Color is useful to determine the foreground and background color for a Form,
Part, Field or Border both in Display as well as in Print Mode,
Color specification can be done by the following ways:
 By specifying the RGB Values (the combination of Red, Green and Blue - each value
should range from 0 to 255)
 By specifying the particular shade or color

152
Dimensions, Formatting & Report Layouts

Syntax
[Color: <Color Name>]
Shade/Color : <Hue>, <Saturation>, <Brightness>
RGB : <Red>, <Green>, <Blue>

While defining a color, only one type should be used i.e. either Shade or RGB.
It does not make sense to use both, since the attribute given at the end will
override the attribute prior to that one.

Shade / Color
One of the ways in which color specification can be done is by using the HSB Standard. HSB
stands for Hue, Saturation, and Brightness. One can create different shades and colors by
varying the percentages of HSB.
This ranges from 0 to 100% and indicates the percentage of the color replaced by white. For
example, 50% means that 50% of the color is white, and 50% the original shade, while 100%
means, that 100% of the color is white, and 0% the original shade – effectively that the shade
value is white, and 0% the original shade – effectively that the shade value is meaningless.
Another viewpoint is to think of the quantum of white as the DECREASE in the PURENESS
of the color (or decrease in the saturation of the color).
Example:
The RGB value equivalent of red color can be specified in HSB standard as follows:
[Color: Red]
Shade : 0%, 100%, 100%
HSB standard for black color
[Color: Black]
Shade : 0%, 0%, 0%
HSB standard for white color
[Color: White]
Shade : 0%, 0%, 100%

153
Dimensions, Formatting & Report Layouts

RGB
This is the second way of specifying the color. One can specify the RGB value from a palette
of 256 colors to obtain the required color. i.e., the values Red, Green & Blue each can range
from 0 to 255. This gives the user an option to select from 24 bit Color.
Example:
[Color: Pale Leaf Green]
RGB : 169, 211, 211

[Field: Party Name]


Set as : $PartyLedgerName
Color : Pale Leaf Green
Print FG : Pale Leaf Green

SysColor
The attribute Syscolor is used to specify the default system colors.
Syntax
Syscolor : < Default system Color>
Default System Color is to specify the default system color

Exercise 5.10
Objective
The objective of the following program to demonstrate the usage of Definition and Attribute
'Border' and 'Style'.

Capabilities Used
 Usage of border and style definition
 Background Attribute at Form and Field Definition
 Style attributes Font, Height and bold
 Color attribute at Field definition

154
Dimensions, Formatting & Report Layouts

Code
[Report: Exer Border and Style]
Form : Exer Border and Style

[Form: Exer Border and Style]


Parts : Exer Border and Style
Background: Yellow

[Part: Exer Border and Style]


Lines : Exer Border and Style

[Line: Exer Border and Style]


Fields : Exer Border and Style

[Field: Exer Border and Style]


Set as : "Welcome 2 Tally"
Style : Exer Style
Border : Exer Border
Background : Petal Pink
Color : Green
;; Style definition to specify the Font, Height and Boldness of the contents wherever this Style is used
[Style: Exer Style]
Font : "Algerian"
Height : 16
Bold : Yes
/* Non Standard Borders that are not declared in Default TDL can be declared to specify the Thickness, Color, etc. of the
Top, Bottom, Left and Right Borders.*/’
[Border: Exer Border]
Top : Thin, Double
Bottom : Thick
Left : Flush
Right : FullLength
Color : Red
;; End-of-File

155
Dimensions, Formatting & Report Layouts

Output

Program Explanation
The report is displayed by using Style and Border definition. The style Exer Style defines one
different style for this TDL and it defines the Font, Height and Bold for the text. Similarly, the
border Exer Border defines a new border by using the attributes Top, Bottom, Left, Right and
color attributes.
The field Exer Border and Style is displayed by using the defined border and style. The
attributes Style and Border helped to apply these style and border to this field Exer Border and
Style.
The attribute Color at field Exer Border and Style is used to give g color to the displayed text
and border.
5.4.2 Color, Background, PrintFG and PrintBG Attribute
Color
Color attribute is used to specify the color for the Field and Border.

Background
Background attribute is used to set the background Color of a Form, Part or a Field in display
mode.

PrintFG
PrintFG attribute is to set the foreground color for the field in print mode. At the border defi-
nition this attribute is used give the color to the border in print mode.

PrintBG
Print BG attribute is used to set Background Color of a Form, Part or a Field in print mode.
Syntax
[Form: <Form Name>]
Background : <Color Name Formula>
Print BG : <Color Name Formula>

156
Dimensions, Formatting & Report Layouts

[Part: <Part Name>]


Background : <Color Name Formula>
Print BG : <Color Name Formula>

[Field: <Field Name>]


Background: <Color Name Formula>
Print BG : <Color Name Formula>
Color : < Color Name>
Print FG : < Color Name Formula>
Example:
[Form: Salary Detail Configuration]
Background: @@SV_CMPCONFIG

[Part: Party Details]


Background: Red
Print BG : Green

[Field: Party Ledger Name]


Background : Yellow
Print BG : Red
Color : Green
Print FG : white

5.4.3 Format Attribute


Format Attribute at Field Definition
Format attribute is used in Field definition, which determines the Format of the value being
displayed/ printed within the Field.
Syntax
[Field: <Field Name>]
Format : <Formatting Values separated by comma>

157
Dimensions, Formatting & Report Layouts

The value for Format attribute varies based on the data type of the Field.
Field of Type Number
Example:
[Field: My Rate of Excise]
Set As : $BasicRateOfInvoiceTax
Format : “No Comma, Percentage”

Field of Type Date


Example:
[Field: Voucher Date]
Set As : $Date
Format : “Short Date”

Field of Type Amount


Example:
[Field: Bill Amount]
Set As : $Amount
Format : “No Zero, No Symbol”

Field of Type Quantity


Example:
[Field: Bill Qty]
Set As : $BilledQty
Format : “No Zero, Short Form, No Compact”

Format Attribute at Collection Definition


In collection definition, the attribute Format adds a column to the table to show specific values
from the object.
Example:
[Collection: GroupCollection]
Format: $Name, 30

In the above example, the attribute Format will display the contents of the table in the
specified width i.e. 30 in this case, If the width of the table is not sufficient for the name to be
displayed, then the contents will be compressed to fit the width.

158
Dimensions, Formatting & Report Layouts

When the collection is a union of collections, the format object in this collection behaves as a
placeholder for the columns. It is mandatory to specify Format attribute in individual collec-
tion when a collection is union of collections.
Example:
[Collection: LedTable]
Collection: DebtorsLedTable, CreditorsLedTable
Format : A, 20
Format : B, 25

In the above example, A and B act as dummy identifiers and the second parameter is width.

5.5 Report Layouts in Tally.ERP 9


In Tally.ERP9 we primarily have the following kinds of Report Layouts which will suffice the
complex requirements of Data Display. The attributes discussed above will be used in con-
junction with the various other attributes to design the Interface for these layouts. In this
section, we will introduce you to the various layouts available. These will be covered in detail
in the Reporting chapter.
Normally a business requires Reports in any of the following formats:
 Tabular Report : A Report with fixed number columns
 Hierarchical Report : A Report designed in successive levels or layers
 Columnar Report : A Report with (dynamically) varying number of columns

5.5.1 Tabular Report – Eg: Ledger Vouchers


A Tabular Report has the simplest format of all the Report formats. A typical Tabular Report
will have following components:
 Report Title : It contains the Name of the Report, the Title for each column, the
Day/Period for which a Report is generated, etc
 Report Details : It contains the actual information
 Report Total : It contains the Total of the respective columns

In a typical Tabular Report, the number of columns is fixed and is interactive i.e. an end user
can change the appearance of the Report. The Day Book, Stock Summary, Trial Balance,
Group Summary, Ledger Vouchers are the some of the default Tabular Reports in Tally.ERP 9.

159
Dimensions, Formatting & Report Layouts

A typical Tabular Report will have a Title Line, Details Line and an optional Total Line. The
Details Line will be repeated over the objects of a Collection.
A Tabular Report can be made Interactive by adding the following features.
 Adding Buttons to change the period, to change the contents of the Report, etc..
 Adding explosions to the lines

5.5.2 Columnar Report, Eg: Sales Register


The reports in which the number of columns added or deleted as per the user inputs are
referred to as column based reports. There are four types of column-based reports in Tally,
namely Multi-Column Reports, Auto-Column Reports and Automatic Auto-Column Reports,
Columnar Report.
 Multi column Report - A Multi column Report is a report in which a column is
repeated based on the criteria specified by user.
 Auto column Report - An Auto column report is one in which multiple columns are
repeated by just one click of a button.

160
Dimensions, Formatting & Report Layouts

 Automatic Auto-Column Reports – Automatic auto column reports are used when
the columns are required automatically without the intervention of the user when the
report is opened.
 Columnar Reports – The reports which are displayed in columns are called columnar
reports

5.5.3 Designing a Hierarchical Report, Eg: Trial Balance


A Tally application provides a simple way of navigating from one report to another, which is
commonly referred to as a drill down. A drill down facility moves from one report to the other
to give a detailed view based on the selection in the current report. A user can return to the first
Report from the detailed view. A typical drill down in Tally.ERP 9 starts from the Report and
reaches the voucher alteration screen.

161
Dimensions, Formatting & Report Layouts

162
Chapter 6: Objects, Collections and
Internal Object Structure

6.1 Introduction
As we know TDL is a completely Object Oriented Language. Whether it is creating an
Interface or storing some information in the Tally Database, the fundamental artifact is an
Object. All the Interface and Data storing elements are Objects.
This chapter will give a detailed conceptual understanding of Objects & Collections and the
Collection Capabilities in terms of fundamental Data gathering and processing element of
TDL.
Let us begin our discussion by understanding the concept of an Object in general. As we
progress we will take you through the Object Structure and Type of Objects available in TDL.
Then, the focus completely moves on to Collections, its construction, sources and capabilities.

6.2 Objects – In General


Any information that is stored in a computer is referred to as Data. Database is a collection of
information organized in such a way that a computer program can quickly select desired data.
A database can be considered as an electronic filing system. To access information from a
database a Database Management System (DBMS) is used. DBMS allows to enter, organize,
and select data in a database. The organization of data in a database is referred to as the
‘Database Structure’. The widely used database structures are hierarchical, relational, network
and object-oriented.
From the various database structures, most commonly used are hierarchical, relational, network
and object-oriented.
All information related to an entity is referred as an Object. For instance, An Employee is an
entity bearing properties like Employee Code, Employee Name, Salary, etc. Each entity
contains its own set of values for these attributes.

163
Objects, Collections & Internal Object Structure

Figure 6.1 Employee Structure

Hence, in order to store and to manipulate these information, we need some procedures. These
procedures are termed as Methods which operate on data. Data and Methods combined
together are referred as an OBJECT. Objects are persisted/stored in the Database. There can be
relationship established between various Objects which can be maintained and defined as per
the Database Structure adopted.
Tally follows a hierarchical Data Structure. We will discuss the hierarchical Data Structure in
detail under the subsequent section “Tally Object Structure”.

6.2.1 Tally Object Structure


By design, Tally Database is hierarchical in nature i.e. Objects are stored in a tree like struc-
ture. Each node in the tree can be a tree in itself. In this structure, a parent can have multiple
children however every child can have only one parent. A child can further have multiple
children. All the characteristics of a child are inherited from its parent and no child can exist
without a parent.
Multiple Objects are collectively referred as a Collection. In other words, a Collection
contains Multiple Objects where an Object can further contain Methods and Collections.
Methods are used to retrieve stored values and Collection consists of further objects. The
following diagram clearly demonstrates the Hierarchical Data Structure of Tally.

164
Objects, Collections & Internal Object Structure

Figure 6.2 Tally Object Structure

Whether it is an Interface that is to be created or a Data that needs to be persisted into the Tally
DataBase, the object follows a hierarchical structure.
In order to construct a Report, we can have a form which may contain multiple parts, each part
subsequently can contain multiple lines which in turn is made up of fields. Based on the con-
tainership a complete hierarchy of Interface Objects is created.
Similarly, all the data which is persisted into the Tally Database has a predefined hierarchy.
Any manipulations to the existing data needs to strictly adhere to the hierarchy.
Let us understand the Database Object Structure with an example of Ledger object

165
Objects, Collections & Internal Object Structure

Figure 6.3 Ledger Object Structure

In the above figure Ledger is the Base/Primary object. This object has methods Name, Parent ,
Opening Balance and a Collection of Secondary Object Ledger Bill Allocations which can
further contain multiple opening bills. Each Bill Allocation Object further has Methods,
Name, Bill Date, Bill Due Date, and Bill Amount. These Bill Allocation Sub Objects are col-
lectively referred to as Bill Allocations collection.

6.2.2 Object Types


As we already know, that whether an Interface needs to be constructed or the data needs to be
stored/manipulated TDL uses Objects. Let us now understand the classification of Objects
based on its application and usage in various aspects.

166
Objects, Collections & Internal Object Structure

This is pictorially represented below:

Figure 6.4 Object Types

Interface Objects
Objects that are used for rendering the User Interface are Interface objects. Report, Form, Part,
Line, Field, Menu, Table and Button are Interface objects. Interface objects like Report and
Menu are independent items and can exist on their own. The objects Form, Part, Line, Table
and Field comes to existence only when they are contained by their parent in the Interface
Object hierarchy chain.
Data Objects
A data object is a region of storage that contains a value or group of values. Each value can be
accessed using its identifier i.e., Method or a more complex expression that refers to the sub
objects.

167
Objects, Collections & Internal Object Structure

Every Interface Object is associated with a Data Object to perform various operations like
adding, retrieving or altering information stored in the Data Objects. These Data Objects can
either be Internal Objects or External Objects.

Internal Objects
Internal Objects are objects provided by the platform These data objects which are stored as a
part of Tally Database can be manipulated by Tally user i.e., Data can be added, deleted or
updated from within Tally. There are several Internal Objects like Company, Group, Ledger,
Stock Group, Stock item, Unit of measure, Voucher Type, Cost Category, Cost Centre, Budget
and so on.

TDL/External Objects
Objects which cannot be stored as a part of Tally Database are classified as External Objects
and are used for some intermediate data manipulations and temporary storages. These objects
are further categorized as
 Static Objects
 Dynamic Objects

Static Objects are objects hard coded in the TDL code and can be used for some specific
purposes like accepting Inputs from the user during Auto Column Reports, displaying in a
Report etc. These objects can neither be added nor be altered by the Tally user.
Dynamic Objects are temporary Objects created in memory for performing various manipula-
tions. The associated values for these objects can change during the execution of Tally. The
source of these objects can be from a variety of Data Sources like ODBC, XML, DLL and so
on.

Dynamic Objects will be discussed in detail under the section “Populating a


Collection”

6.3 Collections
The fundamental Data gathering and processing element of TDL is the Collection definition.
The bulk of aggregation, chaining and integration capabilities are delivered using Collections.
A collection is a group of Objects/Collections. The source of Objects in the collection can be
either an Internal/TDL Object. Each Object in the Collection follows a hierarchical structure
i.e., it can further contain sub collections within itself.
A collection is created using the Collection definition.

168
Objects, Collections & Internal Object Structure

Syntax
[Collection : <Collection Name>]
Where, <Collection Name> is the identifier assigned to the desired Collection of Objects.
Example:
[Collection : NewTDLCollection]
6.3.1 Simple and Compound Collection
As we have already seen, a collection is a group of multiple Objects/Collections, where each
Object can contain multiple methods and subcollections.
Based on the type of Collections available in TDL, its usage in Default TDL/Source Code and
constituents we can classify them as
 Simple Collections
 Compound Collections
Simple Collection has multiple Objects which contain a single method and contains zero sub-
collections. Default TDL Collections, Name and Address are examples of Simple collection.
Compound Collection has multiple objects containing multiple methods and sub-collections.
Ledger and Stock Item are examples of compound collection.

6.3.2 Populating a Collection


The data processing artifact in TDL provides extensive capabilities to construct and gather
data from various data sources such as Collection of Internal Objects, Collection of TDL
Objects, Collection of Objects available through ODBC Driver, Collection of Objects from
HTTP XML, Collection of DLL Objects. It is also possible to construct a collection by Aggre-
gating/Grouping data from lower levels in the Object hierarchy chain. We can create a collec-
tion of selected/unselected objects in a Report, Parent Report or from a Variable as well.

Using Internal Objects


As we are aware, Internal Objects are objects pre-defined by the platform. We can populate
internal objects using attribute ‘Type’ for the collection. This attribute determines the Type or
Sub-Type of Object the collection will hold.
Syntax
[Collection : <Collection Name>]
Type : <Object Type>: [<Parent Type>]
Where,
<Object Type> is name of Primary Object or its Sub-Type
<Parent Type> is the name of the Parent object of Sub-Type. This is an optional parameter
and requires to be specified only if Object Type is a sub-collection type

169
Objects, Collections & Internal Object Structure

If both Object Type and Parent Types are specified and if current object context
does not belong to the Parent Type, then Attribute Child Of is mandatory which
acts as an identifier to the Parent Type.

Primary Objects
Collection gathered using primary objects directly.
Example:
[Collection : LedgerList]
Type : Ledger
The above code snippet indicates Collection, Ledger list consists of Ledger objects
Sub Objects
Collection gathered using sub collection/secondary collection.
Example:
[Collection : Ledger Vouchers]
Type : Vouchers: Ledger
Child Of : ##LedgerName
Where Variable LedgerName contains the LedgerName selected by the user thereby
gathering all the vouchers of the selected ledger.

We will be taking up more examples in the section on “Basic Capabilities”

Example of Internal Objects


Let us learn to populate Internal Objects
Exercise 6.1:
Objective
The objective of this program is to render the list of Ledgers along with their Group Names
and Opening Balances.

170
Objects, Collections & Internal Object Structure

Capabilities Used
 Attribute Type utilized at Collection definition to specify Internal Object type
 Attribute Repeat used at Part definition for repeating line on a collection
 Attribute Scroll along with Repeat attribute to allow the data to flow off the screen.
This would enable vertical scrolling.
 Attribute modifier Local has been used for changing field attribute values for a line.
Code
[Report: Exer Coll of Internal Objects]
Form : Exer Coll of Internal Objects
Title: "Collection of Internal Objects"

[Form: Exer Coll of Internal Objects]


Parts : Form SubTitle, Exer Coll of Internal Objects
Local : Field: Form SubTitle: Info: "Collection of Internal+
Objects - Ledger"
[Part: Exer Coll of Internal Objects]
Lines : Exer CIO Title, Exer CIO Details
/*Part Attribute 'Repeat' is used to repeat a line. In this case, ‘Repeat’ repeats the Line for as many objects in the Collec-
tion 'Exer Coll of IO Ledgers'. For every subsequent instance of the line, next object in the Collection becomes the Object
in context */
Repeat: Exer CIO Details: Exer Coll of IO Ledgers
/* To provide a Vertical Scroll Bar. In the absence of this, all the ledgers will be accommodated in a single screen thereby
compressing it and making it difficult to read.*/
Scroll : Vertical
CommonBorder : Yes

[Line: Exer CIO Title]


Fields : Exer CIO LedName
Right Fields: Exer CIO GrpName, Exer CIO OpenBal
Local: Field: Default: Type : String
Local: Field: Default: Align : Center
Local: Field: Exer CIO LedName: Set As: "Name"
Local: Field: Exer CIO GrpName: Set As: "Under Group"
Local: Field: Exer CIO OpenBal: Set As: "Opening Balance"
Border : Thin Top Bottom

171
Objects, Collections & Internal Object Structure

[Line: Exer CIO Details]


Fields : Exer CIO LedName
Right Fields: Exer CIO GrpName, Exer CIO OpenBal
Local:Field : Default: Style: Normal

[Field: Exer CIO LedName]


Use : Name Field
/*Method 'Name' is the method available in the Internal Object Ledger, which renders the Ledger Name in current Object
context. Every subsequent line, different object will be set as the current object context.*/
Set As : $Name
FullWidth : Yes

[Field: Exer CIO GrpName]


Use : Name Field
/*Method 'Parent' is a method of Object Ledger, which renders the Group under which the current ledger object falls.*/
Set As : $Parent
Border : Thin Left

[Field: Exer CIO OpenBal]


Use : Amount Field
/*Method 'Opening Balance' is a method of Object Ledger, which renders the OpeningBalance of the current ledger
object in context.*/
Set As : $OpeningBalance
Border : Thin Left

[Collection: Exer Coll of IO Ledgers]


/*Collection Attribute 'Type' sets the Internal Object for the Collection, in this case, Ledger.*/
Type : Ledger
;;End-of-File

172
Objects, Collections & Internal Object Structure

Output

The report displays all the Ledger Objects of the collection line after line. The line Exer CIO
Title displayed at the top is for showing title for each column.
The line Exer CIO Details is repeated on the Collection Exer Coll of IO Ledgers. This col-
lection holds Ledger Objects. The instance of line Exer CIO Details will be generated based
on number of objects being populated in the Collection.
For Line Exer CIO Title we have used Line Exer CIO Details, so that title line inherits
attributes of detailed line. At title line we are localizing every field and providing the value to
be displayed by making use of attribute Set As. However it would become very difficult for
the developer, incase for all fields we require to change attribute values. Hence we have made
use of keyword ‘Default’ alongwith Local attribute modifier.
In the fields Exer CIO LedName, Exer CIO GrpName and Exer CIO OpenBal, Set as
attribute has been used and methods $Name, $Parent and $OpeningBalance of Object Ledger
has been used as value for display.

173
Objects, Collections & Internal Object Structure

Using External Objects


A collection can be populated using TDL/External Objects gathered from a variety of data
sources. These objects can either be Static/Dynamic. We will now take the various cases of
constructing a collection using the same.
Static Objects
Static Objects are Hard Coded Objects’ as they are hard coded in the TDL and Object manipu-
lations like Addition, Deletion, etc. cannot be performed with these Objects by the Tally user.
These values do not change during the execution of the program. The collection of these
Objects can be created by using attribute ‘List Name’ or ‘Object’.
Collection Attribute – List Name
List Name attribute is used when field input needs to be limited to the given Table or List
Example:
[Collection : NameOfCourses]
List Name : BCom, BBM, BA, BCA, BSc
When we display this collection as a table we would receive the above objects as list i.e.,

Collection Attribute – Object


Attribute Object is used to create a collection using Objects which are created by the TDL pro-
grammer. The definition Object is used to define and assign values to the methods of such
Objects. Object definition may contain zero or more user defined methods. If the Object
contains a Method Name, automatically it is being displayed in the Table else Collection
Attribute Format must be used to display user defined method.
Object is similar to List Name attribute if Objects defined contains only one method to be
displayed in the Table.
Example:
[Collection : CourseDetails]
Objects : Course1, Course2, Course3
Format : $CourseName, 30
We have created a collection using the objects Course1, Course2, Course3 which are defined
subsequently. Format is used to specify the Method Name to be displayed in the table for user

174
Objects, Collections & Internal Object Structure

choice. Symbol Prefix $ is used to extract value from the Method CourseName and 30
indicates the Width to be used for displaying the coursename.
Each Object used in the Collection definition must be defined as shown below:

[Object : Course1]
CourseName: “BCom”
Duration : “3 Years”

[Object : Course2]
CourseName: “Bsc”
Duration : “3 Years”

[Object : Course1]
CourseName: “BBM”
Duration : “4 Years”
CourseName and Duration are user specified methods and values to the right of the colon are
the corresponding method values.
When the above list is displayed for user selection and user selects any course, the correspond-
ing value for Duration can be extracted and displayed to the user.
Example of External Objects
Let us learn to populate External or Hard coded Objects
Exercise 6.2:
Objective
The objective of this program is to render the list of Students, their fees and Date of joining
which are defined as external objects.
Capabilities Used
 Attribute Objects is utilized at Collection definition to specify the external objects
required.
 Object definition has been used to specify the methods and its values for the exter-
nal objects.
 Attribute Repeat used at Part definition for repeating line on a collection.
 Attribute Scroll along with Repeat attribute to allow the data to flow off the screen.
This would enable vertical scrolling.

175
Objects, Collections & Internal Object Structure

Code
[Report: Exer Coll of External Objects]
Form : Exer Coll of External Objects
Title : "Collection of External Objects"

[Form: Exer Coll of External Objects]


Parts : Form SubTitle, Exer Coll of External Objects
Local : Field: Form SubTitle: Info: "Collection of External +
Objects - Students"
[Part: Exer Coll of External Objects]
Lines : Exer CEO Title, Exer CEO Details
Repeat : Exer CEO Details: Exer Coll of EO Students
Scroll : Vertical
CommonBorder: Yes

[Line: Exer CEO Title]


Use : Exer CEO Details
Local: Field: Default : Type : String
Local: Field: Default : Align : Centre
Local: Field: Default : Style : Normal Bold
Local: Field: Exer CEO Name : Set as : "Student Name"
Local: Field: Exer CEO JoinDate : Set as : "Joining Date"
Local: Field: Exer CEO FeePaid : Set as : "Fees Paid"
Border : Thin Top Bottom

[Line: Exer CEO Details]


Fields : Exer CEO JoinDate, Exer CEO Name
Right Fields: Exer CEO FeePaid
Local: Field: Default : Style : Normal

[Field: Exer CEO JoinDate]


Use : Uni Date Field
;; Function 'Date' converts the parameter (String) into 'Date' Data Type
Set as : $$Date:$JoiningDate

176
Objects, Collections & Internal Object Structure

Width : 10
Border : Thin Right

[Field: Exer CEO Name]


Use : Name Field
Set as : $Name
FullWidth : Yes

[Field: Exer CEO FeePaid]


Use : Amount Field
Border : Thin Left Right
;; Function 'AsAmount' converts the parameter (Number/String) into 'Amount' Data Type
Set as : $$AsAmount:$FeePaid

[Collection: Exer Coll of EO Students]


;; Collection Attribute 'Objects' is used to populate the External Objects
Objects : Exer COE Student1, Exer COE Student2, Exer COE Student3,+
Exer COE Student4, Exer COE Student5

[Object: Exer COE Student1]


Name : "Hari"
Fee Paid : 1800
Joining Date : "10/01/2011"

[Object: Exer COE Student2]


Name : "Keshav"
Fee Paid : 2700
Joining Date : "12/02/2011"

[Object: Exer COE Student3]


Name : "Madhav"
Fee Paid : 900
Joining Date : "10/01/2011"

177
Objects, Collections & Internal Object Structure

[Object: Exer COE Student4]


Name : "Krishna"
Fee Paid : 5400
Joining Date : "27/02/2011"

[Object: Exer COE Student5]


Name : "Gopal"
Fee Paid : 3600
Joining Date : "12/02/2011"
;;End-of-file

Output

The report displays all the External Objects of the collection line after line. The line Exer
CEO Title displayed at the top is for showing title for each column.

178
Objects, Collections & Internal Object Structure

The line Exer CEO Details is repeated on the Collection Exer Coll of EO Students. As we
require external objects, we have made use of Object attribute at collection definition Exer
Coll of EO Students and provided comma listed object definition names.
For Line Exer CEO Title we have used Line Exer CEO Details, so that title line inherits
attributes of detailed line. At title line we are localizing every field and providing the value to
be displayed by making use of attribute ‘Set as’. However it would become very difficult for
the developer, in case for all fields we require to change attribute values. Hence we have made
use of keyword ‘Default’ alongwith Local attribute modifier
In an Object definition the first left most string before ‘:’ are the method names i.e., Name,,
Fee Paid & Joining Date for External Objects and the values on the right of the separator are
the method values.
6.3.3 Dynamic Objects
Dynamic Objects are created dynamically from external sources like HTTP XML, DLL,
ODBC, XML File etc. from selected Objects in a Report, Variables and using information per-
taining to a disk Directory. Object manipulations like Addition, Deletion, etc. can be
performed with these Objects by the Tally user. These values change during the execution of
the program. The various attributes used for populating a collection using Dynamic Objects
discussed as below
Using an In Memory Object
A collection can be populated using the attribute New Object which is using an object type
specification as defined by the programmer. This is a very useful capability from the point of
view of In Memory Object manipulations required specifically in editing(alter/create) mode.
The new attribute will independently govern the type of object to be added to the collection
on-the-fly. The following is now supported in collection
Syntax
NEW OBJECT: Type-of-Object: Condition
Where, <Type of Object> is the Object Specification as defined by the Object Definition
<Condition> Object will be populated as per the condition specified
Example:
This collection can be used in a Report opened in Edit Mode (Create/Alter).
[Collection: Coll Customer]
New Object : Customer Data
;; New TDL Object Defined

[Object: Customer Data]


Storage : Name : String
Storage : CustId : String

179
Objects, Collections & Internal Object Structure

;; Compound Collection
Collection : PhoneColl : Phone
Collection : AddressColl : Address

[Object: Phone]
Storage : OfficeNo : String
Storage : HomeNo : String
Storage : Mobile : String

[Object: Address]
Storage : AddrLine1 : String
Storage : AddrLine2 : String

Using HTTP/HTTPS – XML Objects


The Objects of a collection can also be obtained from remote XML using HTTP or HTTPS.
Any data can be gathered from HTTP/HTTPS/web-service using XML request response. The
received XML gets converted automatically to TDL objects and is available natively in TDL
reports as $ based methods. The attributes in collection for gathering XML based data from a
remote server over HTTP or HTTPS are RemoteURL, RemoteRequest, XMLObjectPath, and
XMLObject. Whenever the collection is being referred, the XML Request is sent to the
destined HTTP or HTTPS Server and the resultant XML data is fetched and is populated in the
collection.

The attributes given below are provided specifically for using the source as
HTTP XML. The generic attribute Data Source can also be used for the same
which is discussed subsequently.

Syntax
[Collection: <Collection Name>]
RemoteURL : <HTTP/HTTPS URL Address>
RemoteRequest : <Request-Report-Name>, +
<Pre-Request-Edit-Report> :<Encoding Type>
XMLObjectPath : <Start-node> : <Path-to-start-node>

180
Objects, Collections & Internal Object Structure

XMLObject : <TDL-Object-Name>
Where, Remote URL attribute is used to specify the URL of the HTTP/HTTPS Server deliv-
ering the XML data.
RemoteRequest attribute is used to specify the Report name which is to be sent to the HTTP/
HTTPS Server as an XML Request, if the report requires user inputs, then it has to be accepted
before the request is sent. Pre-request edit report specifies the name of the report which
accepts the user input.
XMLObjectPath attribute must contain the path to walk in the response XML which will be
gathered as Collection Objects and is converted to TDL Objects. By default, root node is
assumed to be the Object Path.
<Start-Node> allows you to specify the name and position of the XML node from which the
data should be extracted. It takes two parameters as follows:
<Node Name> : <Position>
<Path-to-Start-Node> is used to specify the path to reach the <start node> from the root
node.
The path specification is :
<Root-node> : <Child Node> : <Start Pos> : <Child Node>: <Start Pos> …

XMLObject attribute is used to specify the TDL Object specifications with their respective
Data Types .

Using an SQL Object from an ODBC Source


Collection can also gather objects from various databases like Excel, Access, SQL, Oracle,
etc. using the ODBC Interface. Attributes ODBC, SQL and SQL Objects are used for
gathering objects in Collection from External data source using ODBC.
Syntax
[Collection: <Collection Name>]
ODBC : <ODBC Driver Connection Strings; File Path>
SQL : <SQL Select Query>
SQLObject : <TDL-Object-Name>
Where,
ODBC attribute is used to specify the ODBC driver connection strings along with File Name
and Path
SQL Attribute is used to specify the Select Statement for retrieving the required rows of the
Table/Sheet

181
Objects, Collections & Internal Object Structure

SQLObject Attribute is used to specify the corresponding TDL Object specifications with
their respective Data Types.

For the detailed usage and examples refer the document“Tally.ERP 9 – Inte-
gration Capabilities” available in the CD. Here we are focusing only on popu-
lating the collection.

Using Various Data Sources


The attribute Data Source can be used to populate a collection using a variety of external
sources using
 XML available over HTTP/HTTPS
 XML File available over a network
 Output XML from an External DLL
 Specific Objects from Current/Parent Report
 Variable
 Directory
Syntax
Data Source : <Type> : <Identity> [: <Encoding>]
Where,
<Type> specifies the type of data source, File Xml, HTTP XML, Report, Parent Report,DLL
or a Variable
<Identity> can be file path or scope etc depending on the type specification
<Encoding> can be ASCII or UNICODE. This is Optional. The default value is UNICODE.

XML available over HTTP/HTTPS/Network


The Type specification will be File XML/HTTP XML depending on whether this is an XML
available in the network or over an HTTP/HTTPS
Example:1
XML file as data source
[Collection : My XML Coll]
Data Source : File XML : “C:\MyFile.xml”
In the above example the type of file is File XML as the data source is XML file. The
encoding is Unicode by default as it is not specified.

182
Objects, Collections & Internal Object Structure

Example:
HTTP as data source
[Collection : My XML Coll]
Data Source : HTTP XML : “http:\\localhost\MyFile.xml”: ASCII
In the above code snippet the type is HTTP XML as the data source is obtained through
HTTP. The encoding of the file MyFile.XML is ASCII.

Output XML from an External DLL


By using this attribute we can invoke the DLL and convert the returned values into TDL
Objects for further processing. The value returned by the DLL is an XML.
The type specification is this case is Plugin XML or AxPlugin XML. For DLL Objects, Plugin
XML is used for C++ DLL and for DLLs created in VB, VB.Net, etc. applications,
AxPlugin.XML can be used.
Identity in this case is the Class Name
Example:
[Collection: InputXMLCollection]
Data Source : AxPlugin XML : TestDLL.Class1
Input XML : PostReqRep, PreReqRep
In this example, the report PreReqRep accepts the user input and the report PostReqRep
generates the input XML which is sent to the DLL. The XML response received from the DLL
is populated in the collection InputXMLCollection.

Specific Objects from Current/Parent Report


Collection can be created using specific objects from the current and parent report.
The type specification in this case is Report/Parent Report. Identity is the scope specification
keyword and is Selected Lines, UnSelected Lines, Current Line, All Lines, Line and Sorting
Methods.
Example:1
[Collection: Selected Objects from Report]
Data Source : Report : Selected
In the above example, the selected objects of the current report are gathered in the collection
and any further operations can be performed on these Objects.

Example:2
[Collection: Selected Objects from Parent Report]

183
Objects, Collections & Internal Object Structure

Data Source : Parent Report : Selected


In the above example, the selected objects of the parent report are gathered in the collection.

Variable
Collection can be created using the variable elements as a the source. The type specification
in this case is Variable. Identity is the Variable Name
Example:
[Collection: LV List Collection]
Data Source: Variable: SLVEmp
The elements of the Simple List Variable SLVEmp will be available as objects in the collec-
tion LV List Collection.
Directory
The collection can be created using the information pertaining to the contents of the disk
directory/folder. The Type specification in this case is Directory. Identity is the Path of the
Directory
Example:
[Collection: ABC Contents]
Data Source: Directory: "C:\ABC"

6.4 Methods
Information is stored in an object, so that we can re-call the same whenever needed. This
information can be retrieved using methods i.e. storage name prefixed with ‘$’ symbol. Based
on general information required, many methods have been provided by the platform.
However, TDL provides a capability to the developer to create methods. We can classify the
methods as Internal & User Defined/External Methods.

6.4.1 Internal Methods


Methods provided by the platform are known as ‘Internal Methods’. These methods are synon-
ymous with the storages provided to push corresponding values into the Objects. Methods for
the Internal Object Ledger are Name, Address, Parent, Opening Balance. In order to access
the value from methods the access specifier “$” is used.

184
Objects, Collections & Internal Object Structure

In order to have an understanding on the complete schema hierarchy of internal


objects available in Tally, refer ‘Schema’ tab provided within Tally.Developer 9

6.4.2 User Defined / External Methods


TDL Programmers can add further methods to the internal objects. These are referred as
‘External Method’ or User Defined Methods and cannot record any user input in the database
as Internal Objects but they can perform various complex calculations.
Example:
Assuming we require Date of the Voucher in a field, which is an internal method available at
voucher, in a report then we will use the method $Date.
[Field : Voucher Date]
Use : Date Field
Set as : $Date
Example:
Assuming we require VoucherType and Number together in one field in a report wherein we
are displaying all vouchers.
[#Object : Voucher]
VchDetails: $VoucherTypeName + “/” + $VoucherNumber
/*
Here we are modifying Object Voucher and adding an external method name ‘VchDetails’ which evaluates to Combination of
VoucherTypeName and VoucherNumber with a slash
*/
[Field : Voucher Details]
Use : Amount Field
Set as : $VchDetails
6.4.3 Object Association
An expression in TDL is always evaluated in context of the Interface (Requestor) and the Data
Object Associated with the Interface object. To put this in a simpler way let us consider the
point below
 We already know that Report contains a Form, Form a Line and so on. Based on this
a complete Interface Object hierarchy is created.
 Whenever we are displaying/altering information using an Internal Data Object in
the Report, the particular Data Object needs to be associated to the specific Interface

185
Objects, Collections & Internal Object Structure

Object. E.g. If a particular ledger ‚ABC‛ is being altered in a Report, the Report will
be associated to the ledger Data Object ‚ABC‛
 Similarly if all the Data Objects of Ledger are displayed in Report, each line in the
Report will be associated with one specific Ledger Data Object
Each Interface object must exist in the context of a data object. In the absence of any explicit
data object association, Interface object will get associated with an Anonymous object which
is the parent of all data objects. The method value referred to at the Field level will always be
evaluated based on the Data Object associated to it. We will now discuss the various method-
ologies to associate Data Object with the Interface Objects.
Object Association Methodologies
There is an implicit Data Association at the various Interface Object levels based on the data
object context which gets inherited based on the hierarchy generated in Report construction or
subsequent Reports/Functions being called from parent Reports. However, TDL programmer
can explicitly associate Data Objects at various Interface object levels like Report, Part, Line
and Field. Based on the data object associated at interface object, method values will be
retrieved at Field definition
Report Level
A Report usually will be associated with a data object, which it inherits from the previous
Report. In case it is the parent Report and no explicit association exists it will be associated
with anonymous object
Report Attribute-Object
Explicit object association at the Report level is done using the “Object” attribute of the
Report. The attribute ‘Object’ takes the “Object Type” and an additional optional value
‘ObjectIdentifierFormula’. In case no Object Identifier is specified it takes the current Object
context available for association.
Syntax
Object: <ObjectType> [:<ObjectIdentifierFormula>]
Where, <ObjectType> is type of any Primary Object
<ObjectIdentifierFormula> is an optional value and is any formula which evaluates to
name of Primary Object.
Example:1
Associating Report object with the Current Voucher object
[Report : New Sales Format]
Object : Voucher
Example:2
Associating Report object with Ledger “Cash”
[Report : Ledger Details]
Object : Ledger : ##LedCash

186
Objects, Collections & Internal Object Structure

Exercise 6.3:
Objective
The objective of this program is to display Ledger ‘Cash’ alongwith its Group and Opening
Balance

Capabilities Used
 Attribute 'Object' at report level alongwith its identifier to associate data object at
report level.
 At Field Attribute 'Set As' methods $Name, $Parent and $OpeningBalance of Object
Ledger has been utilized.

Code
[Report: Exer Object Association at Report]
Form : Exer Object Association at Report
Title : "Object Association at Report"
/*Object 'Ledger' is associated at the Report with Identifier as 'Cash'. Hence, the subsequent UI definitions will inherit
this Object context as a result of which Methods Name, Parent and OpeningBalance at the Field renders the details about
the Object Ledger 'Cash'. */
Object : Ledger: "Cash"

[Form: Exer Object Association at Report]


Parts: Form SubTitle, Exer Object Association at Report
Local: Field : Form SubTitle: Info: "Object : Ledger : 'Cash'+
associated at Report"
Width : 45% Page

[Part: Exer Object Association at Report]


Lines : Exer OAR Name, Exer OAR Group, Exer OAR OpenBal
Space Left: 2% Page

[Line: Exer OAR Name]


Fields : Long Prompt, Name Field
Local: Field: Long Prompt: Set As: "Name : "
Local: Field: Name Field : Set As: $Name

187
Objects, Collections & Internal Object Structure

[Line: Exer OAR Group]


Fields : Long Prompt, Name Field
Local: Field: Long Prompt: Set As: "Group : "
Local: Field: Name Field: Set As: $Parent

[Line: Exer OAR OpenBal]


Fields : Long Prompt, Amount Field
;; Variable 'SVFromDate' is a default System Variable which holds the 'From Date' value.
Local:Field: Long Prompt: Set As: "Opening Balance +
(as on " + $$String:##SVFromDate + "): "
Local: Field: Long Prompt: Set As: "Opening Balance +
(as on " + $$String:##SVFromDate + "): "
Local: Field: Amount Field: Set As: $OpeningBalance
/*Format 'DrCr' will render the value extracted from the Method 'OpeningBalance' along with Dr (Debit) or Cr (Credit)
as applicable.*/
Local: Field: Amount Field: Format: "DrCr"
Output

This report is displaying details of Cash Ledger Object. At report level we have specified
attribute Object and the second parameter Object Type as Ledger. Optionally we can also
specify Object Identifier after Object Type. Object Identifier can be any formula which
evaluates to the Object name. In current scenario we have specified ‘Cash’.
For current display three lines Exer OAR Name, Exer OAR Group and Exer OAR
OpenBal have been declared at Part Level. Each line is having two fields, one for displaying
label and another for the value.

Part Level
Part inherits its data object from the parent Report or Part by default. In order to explicitly
associate a different Object and override the default association the attribute ‘Object’ and
ObjectEx are used at the Part Level. Also, it is possible to Repeat a subpart over each object of
the Collections also

188
Objects, Collections & Internal Object Structure

Repeating Part over a Collection


To associate a Data Object to Part definition, we can use attribute ‘Repeat’ at parent Part defi-
nition. Every subsequent instance of part, the subsequent Collection Object is associated till all
the Objects within the Collection are exhausted.
Syntax
Repeat : <Part Name> : <Collection Name>
Where,
<Part Name> is the name of the child Part where the association is being established
<Collection Name> is the name of the name of the collection.

Example:1
Associate the part over the ledger object
[Part : TSPL Ledger Object]
Parts : Object Associated Part
Repeat : Object Associated Part : Ledger
Scroll : Vertical
This can be very useful in reports such as Multi Account Single Page printing where more than
one ledger along with their vouchers are being printed in a single page. Within the Part for the
current Ledger, subsequent Parts and Lines with Voucher information for the current ledger
object can be printed.

Exercise 6.4:
Objective
The objective of this program is to render List of Ledgers alongwith their pending bills.
Capabilities Used
 Attribute ‘Repeat’ has been used at part level to repeat sub part over a collection.
 Attribute ‘Repeat’ has been used at sub part level to repeat line over a collection.
 ‘Scroll’ attribute has been used at both the parts to ensure the Text is not shrunk
Code
[Report: Exer Object Association at Part]
Form : Exer Object Association at Part
Title : "Object Association at Part"

[Form: Exer Object Association at Part]


Parts: Form SubTitle Exer Column Title,Exer Object Association at Part

189
Objects, Collections & Internal Object Structure

Local: Field : Form SubTitle: Info: "Object association at Part"


Width: 100% Page

[Part: Exer Column Title]


/*Default Line 'BILL Column' is used to render the Column Titles (Default Title used in Billwise Outstandings)*/
Lines : BILL Column

[Part: Exer Object Association at Part]


Parts : Exer OAP Details
Repeat : Exer OAP Details: Exer List of Debtors

Scroll : Vertical

[Part: Exer OAP Details]


Parts: Form SubTitle, Exer OAP LedBills
Local: Line: Form SubTitle : Invisible: $$NumItems:ExerLedgerBills = 0
Local: Field: Form SubTitle: Info : $Name

[Part: Exer OAP LedBills]


/*Default Line 'BILL Detail' is used to render the Bill Details (Default Title used in Billwise Outstandings)*/
Lines : BILL Detail
Repeat : BILL Detail: Exer Ledger Bills
Scroll : Vertical

[Collection: Exer List of Debtors]


Type : Ledger
/*Function 'GroupSundryDebtors' returns the Group Name (which might have been altered) for the Group 'Sundry Debt-
ors'*/
Child Of : $$GroupSundryDebtors

[Collection: Exer Ledger Bills]


Type : Bills
Child Of : $Name
;;End-of-file

190
Objects, Collections & Internal Object Structure

Output

In this report Form Exer Object Association at Part has a part Exer Object Association at
Part. This part has a sub part Exer OAP Details which is being repeated on a collection Exer
List of Debtors.
Collection Exer List of Debtors is holding Ledger Objects. We have also made use of
attribute ‘Child of’ which would filter Ledger Objects for the specified Parent. In this case we
have made use of function ‘$$GroupSundryDebtors’ which looks for group name Sundry
Debtors in the Ledger Parent.

‘Child of ’locates ledgers that are directly available under Sundry Debtors. In
case you require ledgers under Sub Group also then you need to make use of
attribute ‘Belongs To’.

191
Objects, Collections & Internal Object Structure

The sub part Exer OAP Details has another part Exer OAP LedBills. The part Exer OAP
LedBills has line Bill Detail which is being repeated on a collection Exer Ledger Bills.
Collection Exer Ledger Bills has object of type Bill. Object Bill is dependent on Object
Ledger and cannot be on its own, hence mentioning of attribute Child of for this collection
and the attribute value as Ledger Name i.e. $Name.
Part Attribute – Object
Syntax
Object :<SupplierCollection>:<Index Formula>[:<SeekCondition>]
Where,
<SupplierCollection> This is the name of the Collection of Secondary Objects. Assuming
Primary Object is mentioned at Report Level
<IndexFormula> This can be First or Last keywords or an index number which denotes the
position index of the object. A negative sign denotes reverse search.
<SeekCondition > This is an optional value and is a filter condition to the supplier collection
Example:1
Report is in the Context of Voucher Object and at part level we are associating with first sub
object Inventory Entry without seek condition
[Part: Sample Part1]
Line : Sample Line
Object : InventoryEntries:First
Scroll : Vertical
Example:2
Report is in the Context of Voucher Object and at part level we are associating with Sub object
Ledger Entry with seek condition
[Part: Sample Part2]
Line : Sample Line
Object : LedgerEntries:(-1):@@IsParty
Scroll : Vertical

[System: Formula]
IsParty : $IsPartyLedger

Part Attribute – ObjectEx


The attribute Object Ex provides the ease of using enhanced method formula syntax while
specifying the object association. Now even the Primary Object can be associated to a Part,

192
Objects, Collections & Internal Object Structure

which was not possible with the Object attribute of Part Definition. Taking an example of
Party that we select in a voucher, we require its address from the corresponding Ledger master
Object.
Syntax
ObjectEx : <Method Formula Syntax>
ObjectEx : <Primary Object Specification>.+
[<Sub Object Specification>]
Where,
<Method Formula Syntax> is <Primary Object Specification>.[<Sub Object Specifica-
tion>]
<Primary Object Specification> is (<Object Type>,<Object Identifier Formula>). Since
the specification evaluates to an Object, it should end with a period i.e. (.)
<Sub Object Specification> is CollectionName[Index,<Condition>]. Since the specification
evaluates to an Object, it should end with a period i.e. (.)

i. While using the Method Formula Syntax with Object Ex ensure that it
evaluates to an Object.
ii. The Method Formula Syntax for “Accessing Methods” will be covered in
detail in the subsequent section
Example:1
Report is in the Context of Voucher Object and at Part level we are associating with Stock Item
Object without sub object specification
[Part: Sample Part3]
ObjectEx : (Stock Item, ##IName).

[Variable : IName]
Type : String
Default : “Item 1”

Make a close observation, the Part SamplePart 3 would now be in associated with the
stockitem and as this is a Primary Object Specification it ends with a period (.).

Example:2
Report is in the Context of Voucher Object and at part level we are associating with Ledger
Object with Sub Object Specification for Bill Allocation Collection

193
Objects, Collections & Internal Object Structure

[Part: Sample Part4]


ObjectEx : (Ledger, “ABC”).BillAllocations[1,$Name = “Bills 2”].
The syntax for Primary Object Specification is same, however you can also provide and
extended path to its sub-object, by providing sub collection name and index. Optionally a
condition can also be specified. In the above example the Part is associated with the 1st Bill
allocations object with name “Bills2” for the ledger Object “ABC”
Line Level
To associate a Data Object to Line definition we need make use of attribute ‘Repeat’ at Part
definition. This is one of the most frequently used attributes.
Syntax
Repeat : <Line Name> :[<Collection Name> : +
[<Supplier Collection> : <Index Formula> +
[: Seek Condition]]
Where,
<Collection Name> is the name of the name of the collection. In case the name of the collec-
tion is a subcollection, then the supplier collection details need to be furnished
<Supplier Collection> is the name of the collection one level up in the hierarchy.
<Index Formula> is the position index of the Object in the supplier collection. First and Last
keywords can be used which denotes 1 and -1 respectively
<Seek Condition> is an optional filter which would be applied to Supplier condition
Example:1
The Part Sample Part 1 is in the association of Voucher Object
[Part : Sample Part 1]
Line : Sample Line 1
Repeat : Sample Line 1 : Inventory Entries
Scroll : Vertical
The line Sample Line 1 will be repeated on each object of Inventory Entries collection.

Example:
The Part Sample Part 2 is in the association of Voucher Object
[Part : Sample Part 2]
Line : Sample Line 2
Repeat: Sample Line 2:Batch Allocations:Inventory Entries : First
Scroll : Vertical

194
Objects, Collections & Internal Object Structure

The line Sample Line 2 will be repeated on each object of Batch Allocations collection of
the first Object of the Inventory Entries collection
Repeat Attribute – Method Formula Syntax Support
The Method Formula syntax is also supported for the Collection specification in the Repeat
Attribute
Syntax
Repeat : <Line Name>: <Method Formula Syntax>
Where,
<Method Formula Syntax> is <Primary Object Specification>.[<Sub Object Specification>]
<Primary Object Specification> is (<Object Type>,<Object Identifier Formula>). This
evaluates to a Primary Object.
<Sub Object Specification> is CollectionName[Index,<Condition>]. If this specifies the col-
lection over which the line is to be repeated then the Index and Condition need not be specified
as it evaluates to a specific Object.

While using the Method Formula Syntax with Repeat ensure that it evaluates to
a Collection.

Example:3
The Part Sample Part 3 is associated with the Voucher object.
[Part : Sample Part 3]
Line : Sample Line 3
Repeat : Sample Line 3: (Ledger, “ABC”).BillAllocations
Scroll : Vertical
The line Sample Line 3 will be repeated over each object of the Bill Allocations collection for
the Ledger ABC.

Field Level
By default, Field inherits its object context from its parent UI Object. Field also allows Object
overriding using Field Attribute Object.
Syntax
Object: <ObjectType> [: <ObjectIdentifierFormula>]
Where,
<ObjectType> is type of any Primary Object

195
Objects, Collections & Internal Object Structure

<ObjectIdentifierFormula> is an optional value and is any formula which evaluates to name


of Primary Object.
Example:
[Field: Test Field]
Object : Cost Centre: “R & D”
Here the field is associated with the Cost Centre Object having the name R & D.
6.5 Object Context
An Interface Object is always associated with a Data Object. An Interface Object will either
retrieve data from the Data Object or will store data into the Data Object which is associated.
The Data Object association will be inherited to the subsequent levels in the Interface Object
hierarchy unless it is overridden explicitly at the any specific Object level.
Any expression will be evaluated in context of the Interface Object and the corresponding
Data Object. Methods, Variables and Fields are Leaf components in an expression as other
components like Formulae or Functions finally evaluate into either one of these or result into
constants. A method value is evaluated based on the Data Object and Variable and Field value
is evaluated based on Interface object.
In other words “Context” can be defined as the existing state of an expression on the
basis of which it is evaluated. The Object Context is a combination of the Interface
(Requestor) Object and the corresponding Data Object associated to it.

196
Objects, Collections & Internal Object Structure

6.5.1 Accessing Methods


The methods pertaining to an Object can be evaluated by using the Access Specifier “$”. The
basis for evaluation will be the Data Object context available at the Requestor of the method
expression.
The various techniques available for Method Evaluation are as given below:
 Using Current Object Context
 By Reference
 By Index
 Method Formula Syntax

Using Current Object Context


In order to access a Method using the current Data Object context available we can directly
prefix the method name with a “$”
Syntax
$<Method Name>
Example:
Report is in context of Company Object and email id is required to be displayed in the field.
[Field : Sample Field]
Set as :$Email
The above snippet would display email of the company.

List of objects, collections and its methods have been provided in Tally.Devel-
oper 9 under Schema Browser. Please refer to the same.

Referencing another Object


When the method value needs to be evaluated from an Object context other than the current
Object context, then we can use the referencing mechanism to evaluate the same from another
object.
Syntax
$<Method Name>:<Referred Object Type>:+
<Object Identifier Formula>
Where,
<MethodName> is the name of the method which belongs to <Referred Object Type>
<Referred Object Type> is the name of the primary object

197
Objects, Collections & Internal Object Structure

<Object Identifier Formula> would be a formula that uniquely identifies the Referred Object
Example:
Field is in context of Voucher Object and company’s email is required
[Field : Sample Field]
Set as :$Email:Company:##SVCurrentCompany
The above snippet would display email id of the current company

Using a SubCollection Object


Methods within the sub-objects of the current object context can be accessed by specifying the
Index of the specified object whose method is to be evaluated.
Syntax
$<Method Name>:< Sub Collection Name>: <Index>:+
<filter condition>
<Method Name> This is the Name of the Method which belongs <Sub Collection Name>.
<Sub Collection Name> This is the Name of the Sub Collection of the current Data Object
context
<Index> This is the searching direction. It can either be the First or Last.
<Filter Condition> is the condition applied to the sub collection.

Example:
The current Object context in this case is the Voucher Object.
$LedgerName:LedgerEntries:First
This will retrieve the value of the Method LedgerName from the first sub object LedgerEn-
tries.

Direct Access using Method Formula Syntax


Method Formula Syntax allows us to retrieve values from any object including its sub-collec-
tions to any level without changing the current object context. As this syntax allows retrieving
values from any object it is mandatory to provide complete object path.
Syntax
$<Primary Object Specification>.<Sub Object Specification>.+
MethodName
Where,
<Primary Object Specification> is (<Object Type>,<Object Identifier Formula>).
Primary Objection specification is mandatory only if values are referred from different object.

198
Objects, Collections & Internal Object Structure

<Sub Object Specification> is <SubCollection>[< Index Formula>,< Condition >]


<Index Formula> This should return a number which acts as a position specifier in the Col-
lection of Objects matching the given <condition>
<Method Name> is the name of the Method available in the specified path
The method formula syntax also allows us to traverse towards the primary object or to
different sub object from current object context. The Primary Object Path Specification can
either be:
 Absolute
In an absolute path specification, the Primary Object is explicitly specified using the Object
type and Object identifier.
 Relative
A Relative Path is referred to by using empty parenthesis () or a dotted path to refer to the
Parent object relatively. A SINGLE DOT denotes the current object, DOUBLE DOT the
Parent Object, TRIPLE DOT the Grand Parent Object and so on. The hierarchy referred here
is for the Internal Object.
In the succeeding examples we will take you through various scenarios on usage of the
Method Formula Syntax.

This is a generic syntax which is used to access a method and to associate an


Object at a particular Interface level using Attribute Object and Repeat. We
have seen the usage of this syntax in association in the previous sections. The
specification needs to end in a Method, Object or Collection based on where it
is used.

Example:1
Assuming Voucher Object is the current object. Assuming the current Object Context is
Voucher.
[Field : Sample Field 1]
Set As : $LedgerEntries[1].LedgerName
This is used to retrieve the method LedgerName from the first LedgerEntries object of the
current voucher Object.
Example:2
Assuming the current Object Context is Voucher(Sales Invoice).
[Field : Sample Field 2]
Set As : $LedgerEntries[1,@LedgerCondition].Amount
LedgerCondition : $LedgerName = “Sales”

199
Objects, Collections & Internal Object Structure

This is used to retrieve the method Amount from the first LedgerEntries object with ledger
name Sales of the current voucher Object. Observe the usage of condition in the above syntax.
Example:
Assuming the current Object Context is Voucher(Sales Invoice).
[Field : Sample Field 3]
Set As : $LedgerEntries[1,@LedgerCondition].+
BillAllocations[1].Name
LedgerCondition: $LedgerName = “Acme Corp”
This is used to retrieve the method Name from the first Bill Allocations object with ledger
name Acme Corp of the current voucher Object. Observe the usage of condition in the above
syntax.
Example:4
In the example below the method is evaluated irrespective of the current Object ContexT. Here
the Primary Object specification is mandatory
[Field : Sample Field 4]
Set As : $(Ledger,@PartyLedger).BillAllocations[1].+
OpeningBalance
PartyLedger : “Acme Corp”
This is used to retrieve the method OpeningBalance of the first Bill for the Party Ledger Acme
Corp. Observe the Primary Object Specification for the Ledger Master Object in the above
syntax.

Example:5
Assuming that Batch Allocation is the current object context
[Field : Sample Field 1]
Set as : $...Date
In the Voucher Object hierarchy Batch Allocations is at the third level. Each dot denotes one
level. First dot signifies current object, second dot signifies Parent and third dot signifies
Grand Parent. In the example triple dot is used to reach to the Voucher Object level and
retrieve the method “Date” from there.
This can also be specified alternatively as
[Field : Sample Field 1]
Set as : $().Date
Where,
(). signifies Primary Object in the current internal Object hierarchy

200
Objects, Collections & Internal Object Structure

Example:
Assuming that the current object context is at any level within the voucher object hierarchy
[Field : Sample Field 2]
Set as : $().LedgerEntry[1,@ExpLedGrp].Amount
ExpLedGrp: $IsGroupDirectExpenses:($Parent:Ledger:$LedgerName)
This is used to retrieve the method Amount of the first Expense Ledger Entry Object. Observe
the usage of (). in the syntax. From any level this specification takes to the Primary Object
i.e., the Voucher Object in the above case.
Exercise 6.5:
Objective
The objective of this program is to understand the Dotted Method Syntax.
Capabilities Used
 At report level data Object association is specified by providing attribute ‘Object’
alongwith it’s Identifier.
 At field level attribute ‘Set as’ has been used and various methods are utilized to
fetch values from various data objects
Code
[Report: Exer Dotted Method Syntax]
Form : Exer Dotted Method Syntax
Object : Ledger: "Cash"
Title : "Dotted Method Syntax"

[Form: Exer Dotted Method Syntax]


Parts : Form SubTitle, Exer Dotted Method Syntax
Local: Field: Form SubTitle: Info: "Understanding Dotted +
Method Syntax"
Width : 60% Page

[Part: Exer Dotted Method Syntax]


Lines : Exer DMS Title, Exer DMS CurrObj, Exer DMS +
DiffObjGroup, Exer DMS DiffObjCompany
Local: Field: Default : Style : Normal
Local: Field: Long Prompt: Delete: Align
Local: Field: Long Prompt: Style: Normal Bold

201
Objects, Collections & Internal Object Structure

Local: Field: Long Prompt: FullWidth: Yes


Local: Field: Name Field: Border: Thin Left
Local: Field: Amount Field: Border: Thin Left

[Line: Exer DMS Title]


Fields : Long Prompt
Right Fields: Name Field, Amount Field
Local : Field: Default : Type : String
Local : Field: Default : Style : Normal Bold
Local : Field: Default : Align : Center
Local : Field: Long Prompt: Info: ""
Local : Field: Name Field: Set As: "Group/ Company Address"
Local : Field: Amount Field: Set As: "Closing Balance"
Border : Thin Top Bottom

[Line: Exer DMS CurrObj]


Fields : Long Prompt
Right Fields : Name Field, Amount Field
Local :Field : Long Prompt: Info: "Current Object +
(Ledger, Cash)"
/* Without Object context switching, values are retrieved here since Object of Type Ledger is associated at the Report
with identifier as 'Cash'. Hence, the Methods Parent and ClosingBalance will be retrieved from the Ledger 'Cash' */
Local : Field: Name Field: Set As: $Parent
Local : Field: Amount Field: Set As: $ClosingBalance

[Line: Exer DMS DiffObjGroup]


Fields : Long Prompt
Right Fields : Name Field, Amount Field
Local :Field : Long Prompt: Info: "Different Object +
(Group, Bank Accounts)"
/*Since, we need the details of the Group 'Bank Accounts', we have specified the entire object using Dotted Method
Syntax.*/
Local : Field: Name Field: Set As: $(Group, +
"Bank Accounts").Parent

202
Objects, Collections & Internal Object Structure

Local : Field: Amount Field: Set As: $(Group, "Bank Accounts")+


.ClosingBalance
[Line: Exer DMS DiffObjCompany]
Fields : Long Prompt
Right Fields: Name Field, Amount Field
Local: Field: Long Prompt: Info: "Different Object (Company)"
/*Since, we need the details of the Company, we have specified the entire object using Dotted Method Syntax. Here, we
had to move a level further, i.e., Method 'Address' value from the First Object within the Sub Object 'Address'.*/
Local : Field: Name Field: Set As: $(Company, +
##SVCurrentCompany).Address[1].Address + ", +
" + $(Company, ##SVCurrentCompany).Address[2].+
Address
Local : Field: Amount Field: Set As: 0
Border : Thin Bottom
;;End-of-file
Output

At report Exer Dotted Method Syntax an attribute Object has been mentioned to associate
Object Ledger and have specified its identifier as Cash.
The report displays five lines on the screen. The pre-defined part Form SubTitle has been
added to Form for displaying the text Understanding Dotted Method Syntax, by localizing
the field Form SubTitle at the Form Exer Dotted Method Syntax. The part Exer Dotted
Method Syntax has four lines.
Line Exer DMS Title has three fields and has been used for title.
Line Exer DMS CurrObj has three fields and has been used for displaying value from Ledger
Object. Hence at fields available at this line we directly mention method names i.e., $Parent
and $ClosingBalance
Line Exer DMS DiffObjGroup has three fields and is displaying value of Bank Account
Group Object. Hence at fields we need to specify the entire Object path i.e., $(Group, "Bank
Accounts").Parent and $(Group, "Bank Accounts").ClosingBalance.

203
Objects, Collections & Internal Object Structure

Similarly at line Exer DMS DiffObjCompany we need the details of the Company Address
from Company Object; hence we have to specify the entire object using Dotted Method
Syntax. As we need a value from a sub-Object ‘Address’ we need to move a level further i.e.,
$(Company, ##SVCurrentCompany).Address[1].Address.

Object Context Switching using Functions


A TDL Expression always gets evaluated in the context of an Interface (Requestor) and Data
Object. Whenever a report is constructed an Interface object hierarchy is created i.e. Report
contains a Form, Form contains a Part and so on.
Every Interface Object is associated with a Data Object. In the absence of explicit data object
association, an implicit anonymous object gets associated. A method value is evaluated in
context of the data object and Variable and Field value is evaluated in context of Interface
object.
There may be cases where we would require evaluating these in a context different from the
implicit context (Interface or Data). TDL provides many functions which provide the facility
to either change the Data or Interface Object Context. A change in Data Object context does
not change the current Interface (Requestor) Object context and a change in Interface Object
Context does not change the current Data Object Context.
We can mainly categorize these functions into two categories
 Data Object Context Switching Functions
 Interface Object Context Switching Functions
We will understand the concept of Access Name before we take up the Context switching
functions in depth. Identifying Part and Line Interface object with ‘Access Name’
The attribute AccessName is available at the Part and Line level to identify, access and refer to
the Objects associated to it from any Interface level.
Syntax
Access Name: <Access Name Formula>
Where,
<Access Name Formula> can be a formula and evaluated to string.

Example:1
Access Name at Part Definition
[Part: Sample Part]
Line : Sample Line1
Access Name: “Sample Part”

204
Objects, Collections & Internal Object Structure

Example:2
Access Name at Line Definition
[Line: Sample Line]
Field : Sample Fld1, Sample Fld2
Access Name: "Repeated Line" + $$String:$$Line
When Line Sample Line is repeated over a collection, every Line is uniquely identified by the
assigned Access Name.

Using Access Name in Method Formula Syntax


Access Name can be used in a Method Formula Syntax to evaluate to either a Method/Collec-
tion by using the Data Object associated with the Interface Object identified by the Access
Name. If a method is to be evaluated it is to be prefixed with a $ and the specification should
end with a method name. In case, a collection is required the specification should be end with
a collection name. This is required in case of a Repeat attribute.
Example:1
Line Sample Line has Access Name as Sample Acc Name and in association with Ledger
Object.
[Field: Sample Field]
Set as : $(Line,“MyLineAccessName”).BillAllocations[1].+
OpeningBalance
Field Sample Field displays the opening balance of the first bill of the object associated with a
Line whose access name is Sample Line Acc Name.
Example:2
Part having access name MyPartAccessName is in the context of Voucher Object.
[Part: Sample Part]
Repeat: Sample Line:(Part,“MyPartAccessName”).InventoryEntries
We can repeat a line Sample Line over Inventory Entries of the Voucher Object which is asso-
ciated with Part having the access name MyPartAccessName.
There are two functions $$ObjectOf and $$AccessObj which use Access Name for Data/
Interface Object context switching and will be discussed in the following section.

6.5.2 Data Object Context Switching


Every Interface Object exists in context of a Data Object which is associated to it. As
discussed above, an expression (specifically method value) gets evaluated in context of the
Data Object associated with the Requestor (Interface Object). By using the functions as given
below we can change the Data Object Context for expression evaluation.

205
Objects, Collections & Internal Object Structure

In all the subsequent examples we will be using the Voucher Data Object
hierarchy to demonstrate the various scenarios for Context Change.

$$Owner
$$Owner evaluates the given expression in the context of the parent data object in the Data
Object hierarchy chain
Syntax
$$Owner:<Expression>
Example:1
In the example given below, let us assume that the field Bill Allocations Amount field
(Requestor) exists in context of Bill Allocations Data Object. In order to evaluate the method
Amount from Ledger Entries Object Context we need to use the function $$Owner.
[Field: Bill Allocations Amount]
Set As : $$Owner:$Amount
In the above Field, the Amount Method from parent Object LedgerEntry is set by using Owner
Function.

Example:2
Similarly, let us assume that the current data object context for the field Bill Allocations
Remarks is Bill Allocations and we need to evaluate the Method Narration from Voucher
Object.
[Field: Bill Allocations Remarks]
Set As : $$Owner:$$Owner:$Narration
In the above Field, the Narration from Object Voucher which is 2 levels above the hierarchy is
set using Owner Function twice. In other words, we are requesting the Narration Method from
Owner of Owner.

$$BaseOwner
$$BaseOwner evaluates the given expression in the context of the base/ primary data object in
the Data Object hierarchy chain available with the Report Object.

206
Objects, Collections & Internal Object Structure

Since the entire Data Object hierarchy is cached with the Object associated at
the Report, BaseOwner Function changes the Data Object context to the Object
associated at the Report .

Example:
$$BaseOwner:<Expression>
As per the Voucher hierarchy, let us assume that our current data object context for the field
Bill Allocations Remarks is Bill Allocations. We require Narration value available at Voucher
Object.
[Field: Bill Allocations Remarks]
Set As : $$BaseOwner:$Narration
In the above Field, the Method Narration from the base Object Voucher is set by using
function BaseOwner.

$$PrevObj
$$PrevObj evaluates the given expression in the context of previous data object of the collec-
tion which contains the current data object in context.
Syntax
$$PrevObj:<Expression>
Example:
Let’s assume that a line is being repeated over a collection of Outstanding Bills which is sorted
on PartyName. After every party Info, a Total Line is needed to print the subtotal for current
Party.
[Line: Outstanding Bills]
Option : Partywise Totals : $$PrevObj:$PartyName != $PartyName
[!Line: Partywise Totals]
Add : Lines : At Beginning : Party SubTotal Line

$$NextObj
$$NextObj evaluates the given expression in the context of next data object of the collection
which contains the current data object in context.

207
Objects, Collections & Internal Object Structure

Syntax
$$NextObj:<Expression>
Example:
Let's assume that a line is being repeated over a collection of Outstanding Bills which is sorted
on PartyName. After every party Info, a Total Line is needed to print the subtotal for current
Party.
[Line: Outstanding Bills]
Explode : Partywise Totals : $$NextObj:$PartyName != $PartyName

$$FirstObj
$$FirstObj evaluates the given expression in the context of first data object of the collection
which contains the current data object in context.
Syntax
$$FirstObj:<Expression>
Example:
Let’s assume a line is being repeated over the ledger collection wherein a field, we require the
first object's name to be set.
[Field: First Name]
Set As: $$FirstObj:$Name
In the above example, a Field First Name is set to First Object of Name Method in a Collection

$$LastObj
$$LastObj evaluates the given expression in the context of last data object of the collection
which contains the current data object in context.
Syntax
$$LastObj:<Expression>
Example:
Let's assume a line is being repeated over the ledger collection wherein a field, we require the
last object's name to be set.
[Field: Last Name]
Set As: $$LastObj:$Name
In the above example, a Field Last Name is set to Last Object of Name Method in a Collection

208
Objects, Collections & Internal Object Structure

$$TgtObject
Apart from Interface (Requestor) and current Data Object Context, there is one more context
available with reference to User Defined Functions and Aggregate Collections i.e., the Target
Object Context.
There are scenarios where the expression needs to be evaluated in the context of Target object,
in such cases the $$TgtObject can be used. Using the $$TgtObject values can be fetched from
the target object without setting the target object as the current context object
Syntax
$$TgtObject:<Expression>
In case of User Defined Functions, the object being manipulated is the Target Object.

Example:1
Consider writing a Function to import a Voucher from Excel wherein the Source Object is Col-
lection gathered out of Objects in Excel Worksheet and the Target Object being the Voucher
and its sub objects.
While setting value to Inventory Entries sub object, the Target Object is changed to Inventory
Entries and the Source Object continues to be Excel Objects.
In order to set values to methods, Quantity and Rate, Stock Item context is required since Unit
Information is available for Item. Hence, TGTObject Function is prefixed to the Expression
@BillQty and @BillRate in order to evaluate these Methods in the context of Target Object
which is the Inventory Entries Object.

[Function: Import Voucher]


|
|
|
Local Formula: BillQty : $$AsQty :$ExcelBilledQty
Local Formula: BillRate: $$AsRate:$ExcelItemRate
|
|
90 : INSERT COLLECTION OBJECT : Inventory Entries
100: SET VALUE: BilledQty: $$TgtObject:@BillQty
110: SET VALUE: Rate: $$TgtObject:@BillRate
120: SET TARGET ..
130: SAVE TARGET

209
Objects, Collections & Internal Object Structure

In case of aggregate Collection the object being populated in the resultant collection is the
Target Object.

Please refer to this example only after you complete the chapter on “TDL Pro-
cedural”

Example:2
Consider an example where while populating a summary collection of Sales Voucher, we need
to track the maximum sales amount for each Item with the date on which the maximum sales
triggered.
In the following example, while populating the Summary Collection, Method MaxItemAmt is
being computed for Maximum Amount. Subsequently, Date is also computed by validating if
current object's Amount is greater than previous computed Amount. Since, Maximum Amount
so far is computed and accumulated in the Target Object being populated, we need to access it
using function TGTObject. Hence,$$TgtObject:$MaxItemAmt evaluates the Method Max-
ItemAmt in the context of computed Target Object MaxItemAmt.

[Collection: Src Voucher]


Type : Vouchers : VoucherType
ChildOf : $$VchTypeSales

[Collection: Summ Voucher]


Source Collection : Src Voucher
Walk : Inventory Entries
By : ItemName : $StockItemName
;; The following returns the Date and Amount for an Item on which Maximum sales has happened

Aggr Compute: MaxDate: SUM: IF $$IsEmpty:$$TgtObject:$MaxItemAmt +


OR $$TgtObject:$MaxItemAmt <$Amount THEN $Date ELSE+
$$TgtObject:$MaxDate
;; MaxItemAmt is the method in Target Object hence TgtObject function is used to evaluate the Method
;; MaxItemAmt in Target Object Context
Aggr Compute: MaxItemAmt: MAX: $Amount

210
Objects, Collections & Internal Object Structure

Please refer to this example only after you complete the topic on Aggregation
Capabilities this chapter only.

$$LoopCollObj
We can gather a Collection (Data Collection) in context of each object of another collection
which is known as Loop Collection. To access methods of Loop Collection objects within
Data Collection, $$LoopCollObj is used.
Syntax
$$LoopCollObj:<Expression>
Example:
To see a consolidated list of vouchers across all the loaded companies
[Collection: Company Collection]
Type : Company
Fetch : Name

[Collection: Vouchers of Multiple Companies]


Collection : MultiCmpDB VchCollection : Company Collection
Sort : Default : $Date, $LedgerName

[Collection: MultiCmpDB VchCollection]


Type : Voucher
Fetch : Date, Vouchernumber, VoucherTypeName, Amount,+
MasterID, LedgerName
Compute : Owner Company: $$LoopCollObj:$Name
In the above example, LoopCollObj function, changes the context to the Loop Collection
Objects which is the Company Collection and hence, returns company name.

211
Objects, Collections & Internal Object Structure

Please refer to this example only after you complete the topic on “Loop Collec-
tion” in subsequent section on Collection Capabilities.

$$ReportObject
$$ReportObject evaluates the given expression in the context of the Data Object associated
with the Report Interface Object.
One of the important Use Case of Report Object is its usage in purview of in memory Collec-
tion gathering. Whenever a collection is gathered it is retained in memory with the Data
Object of the current Interface (Requestor) Object. If the same collection is being used in
expressions again and again then it’s beneficial from the performance point of view to attach it
to the Report Object and evaluate it in context of Report Object n number of times. This elim-
inates the need to re-gather the collection every time in context of other Data Objects.
Syntax
$$ReportObject:<Expression>
Example:1
From a Bill Allocations Data Object context, Voucher Number of Report Object Voucher is
required.
[Field: Bill No]
Set As: $$ReportObject:$VoucherNumber
Example:2
In a Report, Sales of each Item against corresponding Parties required.
[Collection: CFBK Voucher]
Type : Voucher
Filter: IsSalesVT

[Collection: CFBK Summ Voucher]


Source Collection: CFBK Voucher
Walk : Inventory Entries
By : PName : $PartyLedgerName
By : IName : $StockItemName
Aggr Compute : BilledQty : SUM: $BilledQty

212
Objects, Collections & Internal Object Structure

Search Key : $PName + $IName

[Field: CFBK Rep Party]


Use : Qty Primary Field
Set as : $$ReportObject:$$CollectionFieldByKey:$BilledQty:+
@MyFormula:CFBKSummVoucher
MyFormula: ##PName + #CFBKRepName
In the above example, ReportObject Function during its first execution retains the collection
within the Voucher Object (which is the Data Object associated with the Report Object).
During the subsequent calls, the method values are fetched from the Objects available in the
Report Data Object instead of re-gathering the entire Collection again. This helps in perform-
ance improvement drastically.

$$ReqObject
$$ReqObject evaluates the given expression in context of the Data Object associated with the
Interface (Requestor) Object. There may be scenarios where during the expression evaluation
the Data Object context changes automatically and all the methods referred to are evaluated in
context of the changed Data Object Context. The Data Object associated with the Interface
(Requestor) Object is lost. Specifically in those cases, where we need to evaluate methods in
context of the data object associated with the Interface (Requestor) Object we will use the
function $$ReqObject.
Syntax
$$ReqObject:<Expression>
Example:
A Report is required to display Ledger-wise Sales Totals

[Field :Fld LedSalesTotal]


Set As : $LedgerSalesTotal

[#Collection : Ledger]
Compute :LedgerSalesTotal :$$FilterAmtTotal :LedVouchrs:+
MyParty: $Amount

213
Objects, Collections & Internal Object Structure

[Collection: Led Vouchers]


Type : Voucher
Filter : OnlySales

[System: Formula]
My Party : $PartyLedgerName = $$ReqObject:$Name
Only Sales: $$IsSales:$VoucherTypeName

In the above example, a new method LedgerSalesTotal is added in the Ledger Object to
compute the Sales Total from all the Vouchers filtered for the current Party Ledger Object. The
Interface Object (Requestor) for this method is the field FldLedSalesTotal. In the Formula
My Party, current Ledger Name must be checked with the Party Ledger Name of the Voucher
Object which is the current Data Object context. The Data Object associated with the
Requestor is the Ledger Object. So, in order to evaluate the method $name from the Interface
(Requestor) Object's Data Object context the function $$Reqobject must be used.

$$ObjectOf
We have the capability to identify a Part and Line Interface Object using a unique Access
Name. A Form/Report can be identified from any level using the Definition Type. The
function ObjectOf is used to evaluate the expression in context of the Data Object associated
with the Interface Object identified by the Access Name.
Syntax
$$ObjectOf:<DefinitionType>:<AccessNameFormula>:+
<Evaluation Formula>
Example:
The Part Cust Object Association is associated with the Ledger Object Customer. It is iden-
tified by the Access Name CustLedger.

[Part: Cust Object Association]


Lines : Cust Object Association
;; Object associated at Part
Object Ex : (Ledger, "Customer").
;; Access Name specified so that this part can be accessible
Access Name: “CustLedger”
/*In some other field across parts, a field can access the methods of Ledger Object associated with part “CustObjectAssociation”
we can use ObjectOf Funtion */

214
Objects, Collections & Internal Object Structure

[Field: Ledger Parent]


Set as : $$ObjectOf:Part:"CustLedger":$Parent

In the above example, Field Ledger Parent from a different Part accesses the method $Parent
from the Ledger object Customer as it is the Object associated with the part Cust Object
Association identified by Access Name CustLedger.

$$Table
$$Table evaluates the expression in the context of the table object which is selected
in the given Field.
Syntax
$$Table:<Field Name>:<expression>
Example: In the code snippet given below, the table is displayed in the field Ledger Name. In
the other fields LedGrp, LedOpBal, $$Table is used to evaluate the methods $Parent, $Open-
ingBalance in context of the Data Object selected in the field “Ledger Name”.
[Field: Ledger Name]
Table : List of Ledgers
Show Table: Always

[Field: LedGrp]
Set as : $$Table: Ledger Name:$ Parent

[Field: LedOpBal]
Set as : $$Table: Ledger Name:$ OpeningBalance

[Collection: List of Ledgers]


Type : Ledger
Format: $Name, 15
Format: $Parent, 10
Format: $ OpeningBalance, 10
Fetch : Name, Parent, OpeningBalance
;; For Remote Client End

215
Objects, Collections & Internal Object Structure

$$TableObj
$$TableObj is similar to the $$Table. The expression is evaluated in context of the Data Object
selected in the Table in the field specified. The difference is that, in case no object is selected
in the Table or expression evaluation fails $$Table returns a blank string. In such a case
$$TableObj returns a logical value (FALSE) as the result
Syntax
$$TableObj:<Field Name>:<expression>
Example:
A Field needs to be skipped based on the selection of the table in a field.
[!Field: VBOrdDueDRNote]
Skip : $$TableObj:VCHBATCHOrder:$$IsOrder
In the above example, if the Object selected in the Field VchBatchOrder is an Object Order,
then the current field needs to be skipped.

6.5.3 Interface Object Context Switching


As we have already discussed, an expression is evaluated in context of the current Interface
Object which is referred to as the Requestor and the Data Object associated to it. We will now
discuss the switching functions which will change the Interface Object Context for expression
evaluation.

Switching the Interface (Requestor) Object Context does not imply a change in
current Data Object.

$$AsReqObj
$$AsReqObj is used to save the Interface (Requestor) context to the current object for the
evaluation of the expression. All the future references done using ReqObject will point to the
saved Interface Object context. The actual requestor is overridden using the function
AsReqObject
Syntax
$$AsReqObj:<Expression>
Example:
In the example below, a Table of Company Vehicles is displayed in a Field Select Vehicle
which exists in context of the Voucher Object. The table is filtered on the basis of Unused
Vehicles

216
Objects, Collections & Internal Object Structure

[Field: Select Vehicle]


;; In Voucher Entry
Table : CMP Vehicles
Storage: VCHVehicle

[Collection: CMP Vehicles]


Type : Company Vehicles : Company
Childof : ##SVCurrentCompany
Format : $VehicleNumber, 20
Format : $VBrand, 10
Title : “Company Vehicles”
Filter : Unused Veh

[Collection: PrevSalesVchs]
Type : Voucher
Filter: Only Sales

[System: Formula]
Unused Veh :$$AsReqObj:$$FilterCount:PrevSalesVchs:UsedVehicle = 0
Used Vehicle : $$ReqObject:$VehicleNumber = $VCHVehicle
Only Sales : $$IsSales :$VoucherTypeName

In the above example


 Field Select Vehicle is the Interface (Requestor) Object, which is associated with
Data Object Voucher.
 Table/ Collection of Company Vehicles is displayed in the Field.
 Table is filtered for Unused vehicles.
 This collection contains the list of Vehicle Numbers which needs to be compared
with the ones used in the previous sales vouchers. Since Requestor is the Field with
the data object Voucher, Function ReqObject will get evaluated in the context of
Voucher Object which is not expected. Hence to make the current collection i.e.,
CMP Vehicles as requestor object for future reference, AsReqObj Function is used.

217
Objects, Collections & Internal Object Structure

 In the FilterCount Function, when the object context changes to the list of sales
vouchers, ReqObject Function evaluates the parameter $VehicleNumber in the con-
text of requestor Collection CMP Vehicles set using AsReqObj Function earlier and
compares the same with the Voucher UDF VchVehicle stored in the respective
vouchers.

$$ReqOwner
$$ReqOwner evaluates the given expression in context of the Interface (Requestor) objects
Owner in the current Interface object hierarchy. For instance, Report is an owner requestor for
Form; Form is an owner requestor for Part and so on. From Line, when ReqOwner Function is
used, the expression gets evaluated in the context of the Part containing the current line.
Syntax
$$ReqOwner:<Expression>
Example:
[#Menu: Gateway of Tally]
Add: Key Item: ReqOwner Sample: W : Alter: ICCF ReqOwner

[Report: ICCF ReqOwner]


Form : ICCF ReqOwner
Variable : VarReqOwner: String: “Keshava”

[Form: ICCF ReqOwner]


Parts: ICCF ReqOwner

[Part: ICCF ReqOwner]


Lines: ICCF ReqOwner

[Line: ICCF ReqOwner]


Fields: ICCF ReqOwner

[Field: ICCF ReqOwner]


Set As : $$FunctoreturnReqOwner
Set Always: Yes

218
Objects, Collections & Internal Object Structure

[Function: FunctoreturnReqOwner]
Variable: VarReqOwner: String: “Madhava”
Variable: Temp: String: $$ReqOwner:##VarReqOwner

01: MSGBOX: ##VarReqOwner : ##Temp


10: RETURN: $$ReqOwner : ##VarReqOwner
In the above example, Variable VarReqOwner is declared & initialized in a Report as well as
a function. From the Field, this function ReqOwnerFunc is referred to perform some computa-
tion and return the result. Since, ReqOwner is used in the Function and Field is the Requestor
Owner for Function, Field walks back the Interface (Requestor) Object hierarchy to fetch the
Variable value. Hence, the Variable value Keshava of the nearest Interface Object i.e., the
Report is returned

$$AccessObj
We have the capability to identify a Part and Line Interface Object using a unique Access
Name. The function AccessObj changes the Interface Object context to the one identified by
the Access name to evaluate the expression The Interface Object being referred to should be
assigned a unique AccessName via Access Name attribute.
Syntax
$$AccessObj:<DefinitionType>:<AccessNameFormula>:+
<Evaluation Formula>
Example:
[Line: ABC]
Access Name : “AccABC”
[Field: XYZ]
Set As: $$AccessObj:Line:“AccABC”:##VarABC
In the example above the function $$AccessObj changes the Interface Object context from the
field XYZ to the line ABC which is identified by Access Name AccABC. The variable value
is evaluated in context of the line ABC.

$$ExplodeOwner
$$ExplodeOwner changes the Interface (Requestor) Object to the Line owning the current
exploded Part and evaluates the given expression i.e., Field and Variable Values in the context
of Interface Object.
Syntax
$$ExplodeOwner:<Expression>

219
Objects, Collections & Internal Object Structure

Example:
In the following example, Field NameField is being evaluated in the context of Line Smp
InvEntries which owns the current exploded part Smp Expl Part

[Line: Smp InvEntries]


Fields : Name Field
Local : Field: Name Field: Set As: $StockItemName
Explode: Smp Expl Part

[Part: Smp Expl Part]


Lines : Smp Batch Allocations
Repeat : Smp Batch Allocations: Batch Allocations
Scroll : Vertical

[Line: Smp Batch Allocations]


Fields : Name Field
Local : Field: Name Field: Set As: $$ExplodeOwner:#NameField

$$PrevLine
When the line is repeating, we may require evaluating an expression in context of the previous
line. For example, we might require fetching the field values stored in previous line for an
expression in the current line. The function PrevLine is used to change the Requestor to the
Previous Line for expression evaluation.
Syntax
$$PrevLine:<Expression>

The PrevLine function not only changes the Interface (Requestor) Object
context but also changes the Data Object context to the Object associated with
the Requestor

220
Objects, Collections & Internal Object Structure

Example:
In the following example, in case of repeated lines where subtotals are required to be
displayed or printed for same party, we can explode a subtotal line after comparing previous
line’s Ledger and current line's Ledger. If the field values are not the same, then subtotal line is
exploded.

[Line: PrevParticulars]
Explode : PrevParticulars ExpPart : $$PrevLine: #PartyParticulars+
!= #PartyParticulars
$$PrevFld
$$PrevFld is used to extract the value of the filed in the previous field. This is useful in Multi
column reports where this function is used to get the value of the previous field or to find the
difference between two previous fields. The function $$PrevFld without any parameter
retrieves the value of previous field. It can optionally accept a single parameter which
specifies the field number the value of which is to be extracted
Syntax
$$PrevFld:<Expression>
Example:
[Line: Ledger Line]
Field : Ledger Name, Prev Fld Name

[Field: Ledger Name]


Set as : "ABC Enterprises"

[Field: Prev Fld Name]


Set as : $$PrevFld
In the above example the function $$PrevFld (or $$PrevFld:0) will display the value ABC
Enterprises (i.e. value of Previous field Ledger Name)

6.6 Collection Capabilities


Collection -The Data Processing Artifact of TDL delivers immense capabilities in terms of
 Data Retrieval/Extraction
Various attributes/actions provided help in populating a collection by using Internal Object
Types and also to push data into the same. The Filtering capabilities allow conditional retrieval

221
Objects, Collections & Internal Object Structure

of specific data as well. Also, the searching and indexing capabilities facilitate faster retrieval
enhancing the performance improvements.
 Data Presentation
The various processing attributes allow aggregation, chaining, combining and sorting facilities
which are largely focused on advanced presentation of data as per complex business require-
ments.
 Integration
The various attributes allow the retrieval of data into collection from external data bases
available oves like HTTP/HTTPS/ODBC/DLL etc.

In this part of the book we will concentrate on the first two points only. Integra-
tion capabilities will be covered in the second part of the book on Integration
Capabilities.

6.7 Basic Capabilities


6.7.1 Data Retrieval/Extraction
We have covered this capability in the previous sections on Populating the Collection.
Declaring Required Methods
Attribute – Fetch
After specifying the Objects on the basis of which collection is constructed, it is mandatory to
specify the required methods which are to be accessed from the Objects. Fetch attribute is used
to specify the required methods. The methods names are necessarily the Internal methods
available by default.
Syntax
Fetch : <Existing-Method-Name-in-Source>
Where,
<Existing – Method Name in source> refers to the methods, sub objects and UDFs of the
current object which are gathered in the Collection.
Example:
[Collection : Vouchers]
Type : Voucher
Fetch : Date, Narration
However it would be difficult to specify each and every method from the current object. Also
fetching only the method names of a collection is not sufficient, we do require its sub-collec-
tion and its methods. Hence wild cards can be used.

222
Objects, Collections & Internal Object Structure

The two wild characters can be used in Fetch attribute specification ? and *
 ? is used to fetch all the methods of Object in current context.
 * is used to fetch all the methods and sub collections of the Object in context.
Example:1
To fetch all methods of Object
[Collection : Vouchers]
Type : Voucher
Fetch : ?
Example:2
To fetch all methods and sub-collections of Voucher Object
[Collection : Vouchers]
Type : Voucher
Fetch : *
Example:3
To fetch the methods Date, VoucherNumber, Narration and all the methods of collection
Inventory Entries
[Collection : Vouchers]
Type : Voucher
Fetch : Date, VoucherNumber, Narration, InventoryEntries.*

Attribute – Compute
The specification of all internal methods which are required is handled by the Fetch Attribute.
In case, the external methods which are to be computed for each object of the collection, the
same needs to be specified by using the “Compute” attribute.
Syntax
Compute : <Method-Name> : <Method-Formula>
Example:1
The internal method can be accessed by a different name by using Compute
[Collection : Vouchers]
Type : Voucher
Compute : VchDate : $Date
Example:
The parent of the ledger and Stock item is computed at each object level of the Voucher by
referring to the corresponding Stock Item/Ledger Master.

223
Objects, Collections & Internal Object Structure

[Collection : Vouchers]
Type : Voucher
Fetch : LedgerName
Compute : LedParent : $Parent:Ledger:$LedgerName
Compute : ItemParent: $Parent:StockItem:$StockItemName

In this example the LedParent and ItemParent is computed for the first Object
of the subcollections “Ledger Entries” and “Inventory Entries”.

6.7.2 Union and Looping


As we already know, multiple objects of the same type are gathered in a Collection. However
at times it is insufficient for a report to have objects from only one Object type. We may
require to construct a collection which combines the Objects of multiple collections. This
operation is termed as a Union. We will be referring to the final collection in all our explana-
tions as a “Resultant Collection”. Each component collection which is used to arrive at the
resultant collection is referred to as a “Data Collection” There are two ways in which the
resultant collection is constructed

 By specifying a list of Data Collection Only where each Data Collection is discrete
in itself. This is referred to as Union Pictorially shown as below

224
Objects, Collections & Internal Object Structure

The attribute Collection is used to specify the various Collections. This attribute combines all
objects belonging to various collections within a single collection.
Syntax
Collection : <List of Data Collections>
Where,
<List of Data Collections> is a comma separated list of collection.
Example:
[Collection : GroupAndLedger]
Collections : AllGroups, AllLedgers

[Collection : AllGroups]
Type : Group

[Collection : AllLedgers]
Type : Ledger
In the above example, the Resultant Collection “GroupAndLedger” consists of all Objects of
Groups as well as Ledgers.
 By specifying a list of Data Collections where the same Data Collection is repeated
over each Object of another Collection. This is referred to as Looping

225
Objects, Collections & Internal Object Structure

TDL gives developer a capability to dynamically gather data collections in context of each
object of another collection. ‘Collection’ attribute accepts two additional optional parameters
i.e. Loop Collection Name and Looping criteria.
The collection names in the list of collection are referred as Data Collections. The collection
on which the repetition is done is referred as Loop Collection. The collection in which data is
populated is referred as Resultant Collection.
Each data collection is gathered once for each object in the loop collection. If there are n
objects in the loop collection, the data collections are gathered n-times in the context of each
object in loop collection. In the resultant collection objects are delivered as TDL Objects. This
makes it mandatory to fetch the required methods in the Data Collection

226
Objects, Collections & Internal Object Structure

Syntax
Collection : <List of Data Collection>[:<Loop Collection Name>+
[:<Condition for Loop Collection]]
Where,
<List of Data Collection> is comma separated list of data collections.
<Loop Collection Name> is the name of loop collection and it is optional.
<Condition for Loop Collection> is optional. The condition is evaluated on each object of
the Loop Collection.
Example:
The resultant collection will contain all the Voucher Objects for all the Companies that are
loaded

[Collection : All Company Vouchers]


Collections : All Vouchers : All Companies

[Collection : All Vouchers]


Type : Voucher
Fetch : Date, VoucherNumber, VoucherTypeName, Amount, +
MasterID, LedgerName
Compute : CompanyName: $$LoopCollObj:$Name

[Collection All Companies]


Type : Company
Fetch : Name

6.7.3 Filtering
If it is required to retrieve only a specific set of objects from a Collection, then the collection
needs to be filtered. Filtering is applied on the Collection based on a condition. All the objects
which satisfy the given condition are retrieved and are available in the Collection.

227
Objects, Collections & Internal Object Structure

In TDL filter is applied on the collection and all the objects that satisfies the given condition is
retrieved and populated in the collection. Attributes Child Of, Belongs To and Filter are
available to filter. Pictorially represented as below :

Attribute – Child of
Attribute Child Of is a context sensitive attribute. The ChildOf attribute helps to control the
display of the contents of a collection. It retrieves only those objects whose direct parent is the
string specified as the parameter of this attribute.
We have already covered that the “Type” attribute for collection can be specified in two ways
Type : Primary Object Type
Or
Type : Sub Type: Primary Object Type
Syntax
Child Of : <String Formula>
If the collection is constructed using the first syntax the expression in Child Of must evaluate
to Identifier for the parent of the Primary Object Type.

228
Objects, Collections & Internal Object Structure

Example:
If the Type is Object Ledger, then the Child of can evaluate to Sundry Debtors to gather all the
ledgers under the Group Sundry Debtors.
[Collection : My Collection]
Type : Ledger
Child Of : $$GroupSundryDebtors
If the collection is constructed using the second syntax the expression in Child Of must
evaluate to Identifier for the Primary Object Type.

Example:
If the Type Attribute contains SubType as Vouchers and Primary Object Type as Ledger then
Child of attribute must identify the ledger name for which all the vouchers will be gathered. If
the Object Context for the primary Object Type is available, then the Child Of specification is
optional.
[Collection : My Collection]
Type : Voucher : Ledger
Child Of : “ABC led”

Attribute – Belongs To
The attribute Belongs To is used along with the ‘Child Of’ attribute. This attribute determines
whether to retrieve the first level of objects under the value specified in Child Of or include all
the objects upto the lowermost level .BelongsTo takes a logical value.
Syntax
Belongs To : <Logical Value>
Where,
<Logical Value> can either be Yes or No
Example:
To gather all the ledgers under Sundry Debtors including its sub-groups, the following can be
done
[Collection : My Collection]
Type : Ledger
Child Of : $$GroupSundryDebtors
Belongs To: Yes
\

229
Objects, Collections & Internal Object Structure

Filter
The attribute ‘Filter’ is used to specify the condition for filtering the objects. The Filter
attribute takes a system formula which evaluates to a logical value. The condition is specified
in the formula. If more than one filter has to be specified it can be separated by a comma. All
the Objects which fulfill the filter condition are populated in the collection.
Syntax
Filter : <FilterName>
Where,
<Filter Name> is the name of a system formula.
Example:
The collection needs to be gathered with all Sundry Debtor ledgers whose name contain Ltd.
Or Limited
[Collection : LtdDebtors]
Type : Ledgers
ChildOf : $$GroupSundryDebtors
BelongsTo : Yes
Filter : NameFilter

[System: Formula]
NameFilter : $Name contains "Ltd" OR $Name contains "Limited"
First the ChildOf is applied to filter all Sundry Debtor Ledgers and then an additional filter
NameFilter is applied to to get only those ledgers whose name contains “Ltd” or “Limited”.

Filter can filter values biased on any Methods or UDF values within the current
object whereas Child Of can only accept specific object identifiers as specified
by the platform.

6.7.4 Sorting
Sorting is a process of arranging objects in a specific order. Objects of a collection can be
sorted by specifying the sort sequence using the ‘Sort’ attribute. Sorting can be done on
multiple fields both in either ascending or descending order. For descending order, Negative
symbol must be prefixed.

230
Objects, Collections & Internal Object Structure

Syntax
Sort: <Sort Name> : <List of Expressions>
Where,
<List of Expressions> is a comma separated list of expression i.e. Method names, Formula
and Variable. The default sort order is ascending. For sorting in descending order pre-fix the
expression with a negative sign.
Example:
[Collection: My Collection]
Type : Ledger
Sort : Default : $ClosingBalance, -$Name
In the above collection, sorting will happen firstly on Closing Balance method in ascending
order and then by Name in descending order
This is shown in the table as below:
Original Collection before Sorting
Name Closing Balance
Global Traders 10,000
Prism Softlinks 25,000
Universal Computers 10,000
Arvind Kumar 12,500
Fortune Computer Services 5,000
Janata Timbers 7,000
Resultant Collection after Sorting on Closing Balance
Name Closing Balance
Fortune Computer Services 5,000
Janata Timbers 7,000
Global Traders 10,000
Universal Computers 10,000
Arvind Kumar 12,500
Prism Softlinks 25,000
In the above table of sorted objects, please observe that when both the objects Universal
Computers and Global Traders contain the same Closing Balance, the Objects are further
sorted on Name in descending order.

231
Objects, Collections & Internal Object Structure

6.7.5 Searching
Collection capabilities enable indexing of objects based on some unique Key. Whenever a col-
lection is indexed on a particular method, it allows instant access to the corresponding values
without a complete scan. ‘Search Key’ attribute is used to specify the Keys which is indexed
for instant access. This implies that a unique key is created for every object which can be used
to instantly access the corresponding objects and its values.
Syntax
Search Key : <Combination of Method name/s>
Where,
<Combination of Method name/s> are method names separated by ‘+’
The function $$CollectionFieldByKey is used to retrieve values from a collection based on the
key specified.
Syntax
$$CollectionFieldByKey:<Method Name>:<Key Formula>:+
<Collection Name>
Where,
<Method Name> is the name of the method
<Key Formula> is a formula that can be mapped to the methods in the current context as
defined in the search key
<Collection Name> is the collection name in which the Objects are available with their
unique Keys as identifiers
Example:
[Collection: My Ledgers]
Type : Ledger
Fetch : Name, ClosingBalance
Search Key : $Name

[Field : My Closing Bal Field]


Set as :$$CollectionFieldByKey:$ClosingBalance:@MySearchKey:+
MyLedgers
MySearchKey: #LedName
In the above example we have assigned the Method Name as the unique search key for the col-
lection MyLedgers. In the Field the value of $ClosingBalance is retrieved based on the name
of the ledger. In this case the retrieval is much faster as compared to ordinary retrieval using

232
Objects, Collections & Internal Object Structure

other functions like FilterValue or CollectionField. This capability is also very powerful in
case of matrix reports were two or more dimensions need to be represented as rows and
columns. In such case, search key is made up of combination of methods which helps the
retrieval fast since all the keys are indexed and when the matrix value at certain point is
required, it need not search the collection but can directly pick up the Indexed Object with the
help of given Key.
6.7.6 Grouping & Aggregation
The language capability facilitates the creation of large summary aggregated objects very fast
in a single operation which allows the developer to walk down the object hierarchies and
gather values to summarize them in a single scan. The attributes used for aggregation and
grouping are Walk, By and AggrCompute.
The picture below will give clarity on what is meant by Grouping & Aggregation.
Original Collection before Aggregation
Student Name Subject Marks
Krishna English 100
Radha Maths 95
Gopal English 75
Krishna Maths 97
Krishna Science 75
Radha English 90

Resultant Collection after Aggregation by Student Name


Student Name Total Min Max
Krishna 252 75 97
Radha 185 90 95
Gopal 75 75 75
In the above example we have the various rows as listed in the Table Source. These rows need
to be grouped on the basis of Student Name ie all the rows having the same Student Name
will be grouped together. Based on the grouping, the Total, minimum and maximum of marks
need to be calculated. This is termed as Aggregation. The final set of rows which we achieve
after applying the Grouping criteria and aggregating the required columns is the Table Aggre-
gated.
As we already know Tally follows a hierarchical data structure. In that case we will not have
flat tabular structure as above. The language provides capabilities to walk down the hierarchy
of the Objects available in the Source and perform grouping and Aggregation on the same.

233
Objects, Collections & Internal Object Structure

Let us now discuss the various attributes for achieving the above :
Attribute – Source Collection
Source Collection specifies the collections to be used for source data. Multiple Source Collec-
tions can be used which can either be specified as a comma separated list or can be listed in
several lines. The aggregation and grouping is applied thereafter on the Source Collection
Objects. The final collection which is arrived at is referred to as “Summary Collection” in our
discussions.
Syntax
Source Collection : <Collection name>, <Collection Name> …
Where,
<Collection Name> is any predefined collection, the methods and sub objects of which are
available to the current collection for further processing.
Example:
[Collection: Vouchers Collection]
Type : Voucher

[Collection: Summary Collection]


Source Collection : Vouchers Collection

The ‘Summary Collection’ uses Vouchers Collection as source data

Attribute – Walk
Attribute Walk allows us to traverse the hierarchy of sub objects which are available in the
source. This will generate a set of Objects which are required to be grouped and aggregated.
Walk is optional and if not specified, the first level Objects are only available for aggregation.
Walk can be specified to any depth within the source object. This gives enormous flexibility
and power. The Walk list has to be specified in the order in which they occur in the source
object.
Syntax
Walk : <Sub-Object Type/ Sub-Collection>[, <Sub-Object Type/ +
Sub-Collection> …]
Where,
<Sub–Object Type/Sub-Collection> is the name of the Sub Objects/ Sub Collection.

234
Objects, Collections & Internal Object Structure

Example:
[Collection: Vouchers Collection]
Type : Voucher

[Collection: Summary Collection]


Source Collection : Vouchers Collection
Walk : Inventory Entries
In the Summary Collection, by specifying Walk : Inventory Entries, the aggregation can be
performed on the Objects available by traversing till Inventory entries collection . In case,
Objects pertaining to Batch Allocations are required, then Walk can be written as
[Collection: Summary Collection]
Source Collection : Vouchers Collection
Walk : Inventory Entries, Batch Allocations

Attribute - By
After walking to the desired level and generating the final set of Objects to be aggregated, the
next step is to identify the method on which Grouping needs to be performed. This is termed
as the Grouping Criteria. Attribute ‘By’ allows us to specify the grouping criteria.
Syntax
By : <Method-Name>: <Method-Formula>
Example:1
Grouping objects based on Stock Item name

[Collection: Vouchers Collection]


Type : Voucher

[Collection: Summary Collection]


Source Collection: Vouchers Collection
Walk : Inventory Entries
By : StockItemName : $StockItemName
In Summary Collection, all objects having the same Stock Items Names are grouped. This is
specified with the ‘By’ Attribute.

235
Objects, Collections & Internal Object Structure

Example:2
Grouping objects based on Party Ledger name and then on StockItemName

[Collection: Vouchers Collection]


Type : Vouchers: Voucher Type
Child Of : $$IsSales

[Collection: Summary Collection]


Source Collection : Vouchers Collection
Walk : Inventory Entries
By : PartyLed : $PartyLedgerName
By : StockItemName : $StockItemName
In ‘Summary Collection’, all vouchers objects are grouped first on Party Ledger Name and
then by StockItem Name.

Attribute – Aggr Compute


This is the final step in the whole process where aggregation operations like sum, max, min are
applied to the methods on which aggregation is to be performed. This is done after the
grouping criteria is specified. The aggregation will be done on the Objects which are grouped
together. The Method on which Aggregation is required can be of Data Type Number,
Quantity, Rate or Amount.
Syntax
Aggr Compute : <Method-Name> : <Aggr-Type> : <Method-Formula>
Where,
<Method–Name> refers to the method name assigned to the result of the aggregated method
<Aggr–Type> takes operation to be performed on the given method within the given criteria
i.e. Sum, Max or Min.
<Method–Formula> is the method name on which Aggregation operation needs to be per-
formed.
Example:
After grouping the Voucher Objects on the basis of Party ledger name and Stock item name the
sum of BilledQty needs to be computed.
[Collection: Vouchers Collection]
Type : Voucher

236
Objects, Collections & Internal Object Structure

[Collection: Summary Collection]


Source Collection: Vouchers Collection
Walk : Inventory Entries
By : PartyLedgerName : $LedgerName
By : StockItemName : $StockItemName
Aggr Compute : TotBilledQty : Sum : $BilledQty

This is done by specifying the Aggr Compute attribute. The sum of Billed Qty for StockItem a
particular Party is available with the method name “TotBilledQty” within the Summary Col-
lection.

Exercise 6.6
Objective
The objective of the code is to display a report listing all the Parties with the Count, Sales
Amounts and Dates

Capabilities Used
 Button has been added at the form level for changing period of the report
 Repeat attribute at part level for repeating line over a collection
 Scroll attribute for allowing data to flow off the screen
 Total attribute at part to add field values vertically
 At collection definition attributes ‘Type’, ‘Filter’, ‘Source Collection’, ‘By’, ‘Com-
pute’, ‘Aggr Compute’

237
Objects, Collections & Internal Object Structure

Code
[Report: Exer Grp Aggr and Extr]
Form : Exer Grp Aggr and Extr
Title : "Grouping, Aggregation and Extraction"

[Form: Exer Grp Aggr and Extr]


Parts : Exer GAE Period, Exer Grp Aggr and Extr
Buttons : F2ChangePeriod
Keys : ChangePeriod

[Part: Exer GAE Period]


Lines : Exer GAE Period
Space Bottom: 0.50

[Line: Exer GAE Period]


Right Fields: Name Field
Local: Field: Name Field: Set As: $$String:##SVFromDate +
" To " + $$String:##SVToDate
[Part: Exer Grp Aggr and Extr]
Lines : Exer GAE Title, Exer GAE Details
BottomLines : Exer GAE Total
Repeat : Exer GAE Details: Exer GAE Partywise Sales
Scroll : Vertical
CommonBorder : Yes
Totals : ExerGAETotalSalesCount, Exer GAE Sales Amount

[Line: Exer GAE Title]


Use : Exer GAE Details
Local : Field: Default: Type : String
Local : Field: Default: Align : Center
Local : Field: Default: Style : Normal Bold
Local : Field: Default: Lines : 0
Local : Field: Exer GAE LedName : Set As: "Name of the Party"

238
Objects, Collections & Internal Object Structure

Local : Field: Exer GAE Total Sales Count: Set As: "Frequency +
of Billing" + $$NewLine + "(Count)"
Local : Field: Exer GAE Min Date : Set As: "First Bill Date"
Local : Field: Exer GAE Max Date : Set As: "Recent Bill Date"
Local : Field: Exer GAE Min Sales Amount: Set As: +
"Least Billed Amount"
Local : Field: Exer GAE Max Sales Amount: Set As: "Maximum +
Billed Amount"
Local : Field: Exer GAE Sales Amount: Set As: "Total Sales+
Amount"
Border : Thin Top Bottom

[Line: Exer GAE Details]


Fields : Exer GAE LedName
Right Fields : Exer GAE Total Sales Count, Exer GAE Min Date,+
Exer GAE Max Date, Exer GAE Min Sales Amount, +
Exer GAE Max Sales Amount, Exer GAE Sales Amount
Local: Field: Default: Style: Normal

[Field: Exer GAE LedName]


Use : Name Field
Set As : $ExerGAELedgerName
FullWidth : Yes
Display : Ledger Vouchers
Variable : LedgerName

[Field: Exer GAE Total Sales Count]


Use : Number Field
Set As : $ExerGAETotalSalesBill
Border : Thin Left
Align : Right
Width : 10% Page

239
Objects, Collections & Internal Object Structure

[Field: Exer GAE Min Date]


Use : Uni Date Field
Set As : $ExerGAEMinDate
Border : Thin Left
Width : 12% Page

[Field: Exer GAE Max Date]


Use : Uni Date Field
Set As : $ExerGAEMaxDate
Border : Thin Left
Width : 12% Page

[Field: Exer GAE Min Sales Amount]


Use : Amount Field
Set As : $ExerGAEMinSalesAmt
Border : Thin Left
Width : 12% Page

[Field: Exer GAE Max Sales Amount]


Use : Amount Field
Set As : $ExerGAEMaxSalesAmt
Border : Thin Left
Width : 12% Page

[Field: Exer GAE Sales Amount]


Use : Amount Field
Set As : $ExerGAESalesAmt
Border : Thin Left
Width : 12% Page

[Line: Exer GAE Total]


Use : Exer GAE Details
Local: Field: Default : Style : Normal Bold
Local: Field: Exer GAE LedName: Set As: "TOTAL"

240
Objects, Collections & Internal Object Structure

Local: Field: Exer GAE LedName: Align : Center


Local: Field: Exer GAE Total Sales Count: Set As: $$Total:+
ExerGAETotalSalesCount
Local: Field: Exer GAE Min Date: Set As: ""
Local: Field: Exer GAE Max Date: Set As: ""
Local: Field: Exer GAE Min Sales Amount: Set As: ""
Local: Field: Exer GAE Max Sales Amount: Set As: ""
Local: Field: Exer GAE Sales Amount: Set As: $$Total:+
ExerGAESalesAmount
Border: Thin Top Bottom

[Collection: Exer GAE Sales Vouchers]


Type : Voucher
Filter : Exer GAE IsSales

[Collection: Exer GAE Partywise Sales]


/* Use the Objects of the Collection 'Exer GA Sales Vouchers' as it's Source */
Source Collection: Exer GAE Sales Vouchers
/* Grouping is done on Method 'PartyLedgerName' such that aggregation is done on each party uniquely */
By : Exer GAE LedgerName: $PartyLedgerName
Compute : Exer GAE Group : $Parent:Ledger:$PartyLedgerName
/* Aggregation is done to calculate sum, min and max functions for Count, Dates and Amount*/
/*The following aggregation is done to provide total number of Bills for each party.*/
Aggr Compute : Exer GAE Total Sales Bill: Sum: 1
/* The following aggregation is done to provide the first date of Billing for each party.*/
Aggr Compute : Exer GAE Min Date: Min: $Date
/* The following aggregation is done to provide the last date of Billing for each party.*/
Aggr Compute : Exer GAE Max Date: Max: $Date
/* The following aggregation is done to provide the lowest Bill Amount for each party.*/
Aggr Compute : Exer GAE Min Sales Amt: Min: $LedgerEntries[1].Amount
/* The following aggregation is done to provide the highest Bill Amount for each party.*/
Aggr Compute : Exer GAE Max Sales Amt: Max: $LedgerEntries[1].Amount
/* The following aggregation is done to provide the total Bill Amount for each party.*/
Aggr Compute : Exer GAE Sales Amt: Sum: $LedgerEntries[1].Amount
[System: Formula]
Exer GAE IsSales: $$IsSales:$VoucherTypeName

241
Objects, Collections & Internal Object Structure

Output

At form Exer Grp Aggr and Extr a button F2ChangePeriod has been added to change the
period of the report. The form has two parts. The part ‘Exer GAE Period’ has been added to
show the period of the report.
The part Exer Grp Aggr and Extr has three lines. The topmost line Exer GAE Title is
utilized for displaying column Titles and is using the line Exer GAE Details, so it will inherit
all the attributes of the line Exer GAE Details. At line Exer GAE Title we have localized all
the fields and set the values by using attribute Set as.
At part Exer Grp Aggr and Extr, second line Exer GAE Details has been repeated over col-
lection Exer GAE Partywise Sales.
Collection Exer GAE Partywise Sales is a summary collection. The Exer GAE Sales
Vouchers is the source collection of this collection, which is holding Object Voucher and
filter for all the all sales voucher by using ‘Filter’ attribute. Filter attribute accepts only a
system formula as a value.
As the Objective stated is very clear that we require Parties Bill Count, Total Sales Amount
and Dates i.e., First Bill Date and Last Bill Date, we would utilize By for grouping the values
Party Name wise i.e., further Aggregation would be done uniquely on each party, hence we
have grouped on PartyLedgerName.

242
Objects, Collections & Internal Object Structure

At collection Exer GAE Partywise Sales we would have multiple Sales Voucher and this
would have multiple Party Name and repeated Party Name. We require Party Name just once,
hence we would group on basis of Party Name i.e. method PartyLedgerName. Attribute By
takes two parameters, first Method Name that would be defined by the developer and second
Method Formula which would evaluate to a value and would be hold in the Method Name. In
our example we require Party Name hence we have utilized.
By : Exer GAE LedgerName : $PartyLedgerName
Where,
Exer GAE LedgerName is the method name in which unique values of method formula
would be gathered and $PartyLedgerName is the method formula.
After grouping we require to aggregate the values i.e. we need Count of Bills, Total Sales Bill
Amount, First Bill Date and Last Bill Date. This is done by specifying attribute Aggr
Compute. To count the number of bills we would make use of AggrType Sum.i.e.,

Aggr Compute : Exer GAE Total Sales Bill: Sum: 1


Where,
Exer GAE Total Sales Bill is the method name which holds the summation value
Sum is the pre-defined Aggr-Type for adding values
1 is the method formula syntax.
1 would be added the number of times the Party’s Name is available.
We require the first date when we have billed the party. This can be done by specifying
attribute Aggr Compute alongwith AggrType Min i.e.,

Aggr Compute : Exer GAE Min Date: Min: $Date


Where,
Exer GAE Min Date is the method name available in the collection
Min is the pre-defined Aggr-Type for retrieving the least value
$Date is the method formula
Similarly we can retrieve the last bill date by making use of Aggr-Type Max i.e. ,
Aggr Compute : Exer GAE Max Date: Max: $Date

In order to get the total Bill Amount for each party, we will apply summation of all amounts of
the ledger entry object belonging to the Party from all Vouchers. Observe the usage of the
index 1 with Ledger Entries collection, which is always the first ledger entries object in
respective voucher pertaining to the Party.
Aggr Compute : Exer GAE Sales Amt: Sum: $LedgerEntries[1].Amount

243
Objects, Collections & Internal Object Structure

Union of Summary Collections


There are scenarios where we have Union of multiple collections using the same source col-
lection and each collection walks over its sub objects across different paths and computes/
aggregates the values from sub level.
Example:
The requirement here is to generate a Report displaying Item Wise and Ledger Wise amount
totals for all Vouchers

Using the Union Approach


;;The source collection “Voucher Source” is a Collection of Vouchers
[Collection: VoucherSource]
Type : Voucher
;;The collection using “Voucher Source” as a source collection and walking over Ledger Entries Sub Object aggregating Amount
by grouping over Ledger Name
[Collection: Ledger Details]
Source Collection : VoucherSource
Walk : AllLedgerEntries
By : Particulars: $LedgerName
Aggr Compute : Tot Amount: Sum: $Amount
Keep Source : ().
;;The collection using Voucher Source as a source collection and walking over Inventory Entries Sub Object aggregating Amount
by grouping over Stock Item Name

[Collection: StockItem Details]


Source Collection: VoucherSource
Walk : AllInventoryEntries
By : Particulars: $StockItemName Aggr Compute: Tot Amount:
Sum : $Amount
Keep Source : ().

;;The Resultant Collection which is a union of objects from the above two collections “Ledger Details” and “StockItem Details”

[Collection: Union LedStk Vouchers]


Collection: Ledger Details, StockItem Details
As seen from the example above both the collections Ledger Details and StockItem Details
are using the same Collection Voucher Source. We can observe that while gathering, summa-

244
Objects, Collections & Internal Object Structure

rizing values from the Source Collection, each object of the collection Voucher Source is
traversed twice for aggregating objects over two different paths i.e., once for Ledger Entries
and then again for Inventory Entries. The Report finally uses the Union Collection Union
LedStk Vouchers to render the same.
In such cases, significant CPU cycles will be utilized in gathering and walking over the same
Source Object along different paths more than once.

6.7.7 Performance Improvements – Using Walk Ex


The attribute WalkEx which when specified in the resultant collection, allows us to specify a
collection list. The source collection specification is available in the resultant collection. The
collections referred in WalkEx do not have any source collection specified and contain
attributes only to walk the source collection and aggregate over Sub Objects of an already
gathered collection. The advantage of using WalkEx is that, all walk paths specified in the col-
lection list are traversed in a single pass for each object in the source collection. This results in
improvements in performance drastically.
Syntax
[Collection: <Collection Name>]
WalkEx : <Collection Name1>, <Collection Name2>, …..
Where,
Collection Name1, Collection Name2 are the collection names specifying Walk and aggrega-
tion/computation attributes.

Using the WalkEx Approach


;;The source collection “Voucher Source” is a Collection of Vouchers

[Collection: VoucherSource]
Type : Voucher
/* The collection “UnionLedStkVouchers” is the resultant collection which will contain all the Objects obtained out of walks and
multiple walks over the same Source Collection. The Report finally uses this Collection. The attribute WalkEx is specified which
has values as collection names “Ledger Details” and “StockItem Details”*/

[Collection: Union LedStk Vouchers]


Source Collection: VoucherSource
WalkEx : Ledger Details, StockItem Details
Keep Source : ().
/*The Collection ”Ledger Details” is walked over “AllLedgerEntries” SubObjects and aggregates the amount by grouping over
Ledger Name. Note that the absence of source collection */

245
Objects, Collections & Internal Object Structure

[Collection: Ledger Details]


Walk : AllLedgerEntries
By : VchStockItem : $LedgerName
Aggr Compute : VchLedAmount : Sum : $Amount
/*The Collection ”StockItem Details” is walked over “AllInventoryEntries” SubObjects and aggregates the amount by grouping
over Stock Item Name. Note the absence of Source Collection in this */

[Collection: StockItem Details]


Walk : AllInventoryEntries
By : VchStockItem : $StockItemName
Aggr Compute : VchLedAmount : Sum : $Amount

The Collections used within the WalkEx uses the same Source Collection. Each Object of
Voucher Source is walked across Ledger Entries and Inventory Entries in a single pass.
Thus, there is an exponential improvement in performance as it traverses each object only
once to gather the values for the resultant collection. In the case of Union Collection, for every
Collection using different walk path, the Source Collection Object is being traversed again and
again.

Attribute – Keep Source


As the name suggests, Collection attribute Keep Source retains the source collection objects
with the specified Interface Object . By keeping the source at the relevant Interface Object, the
performance is enhanced to a greater extent as the Source Collection is not re-gathered each
time it is referred. At the same time, if the Collection is not required and Keep Source if spec-
ified, it unnecessarily blocks the memory. Hence, Keep Source is an useful tool if judiciously
used else can effect the performance adversely.
Keep Source accepts a parameter value as Yes, No, … Or (). Each dot specifies parent
Interface object at one level up. For e.g., Parent Interface of Line is Part or another Line. Sim-
ilarly, parent of Exploded Part is a Line from which it is exploded. (). Is the topmost Interface
Object in the current Interface Object hierarchy which may be a Report. Throughout the life of
the Report, the objects of this collection will be available as source unless in some other
summary collection, this is used as a source and Keep Source Attribute is not specified.
Interface Object holds the Source Collection along with the Data Object in the current context.
If no data object is specified, anonymous object holds the Source Collection Objects.

. – Single dot retains the source collection objects in current interface object
.. – Double Dot will retain the source collection objects in current interface object’s parent

246
Objects, Collections & Internal Object Structure

... – Triple Dot will retain the source collection objects in the current interface object’s parent’s
parent and so on
(). –This will retain the source collection objects in the Base Owner of the Interface Object

Syntax
Keep Source : Yes/No/.../().
Example:
Keep the source collection objects in the current Interface Object level
Keep Source : Yes
OR
Keep Source : .

Don’t keep the Source collection Objects


Keep Source : No

Keep the source collection objects in the current object’s parent


Keep Source : ..

Keep the source collection objects in current object’s grand parent


Keep Source :...

Keep the source collection objects with the base owner interface object
Keep Source : ().
6.7.8 Variables in Collection
TDL supports the concept of aggregate/summary collection for creating summarized reports.
In the aggregate collection during the evaluation following three sets of objects are available:
 Source Objects: Objects of the collection specified in the Source Collection
attribute.
 Current Objects : Objects of the collection obtained till the Walk specification is
exhausted
 Aggregate Objects: Objects obtained after performing the grouping and aggrega-
tion
There are scenarios where some calculation is to be evaluated based on the source object or the
current object value and the filtration is done based on the value evaluated with respect to final

247
Objects, Collections & Internal Object Structure

objects before populating the collection. In these cases to evaluate value based on the
changing object context is tiresome and at times impossible as well.
The concept of collection level variables provides Object-Context Free processing. The values
of these inline variables are evaluated before populating the collection.
The variables defined using attributes Source Var and Compute Var can be referred in the col-
lection attributes By, Aggr Compute and Compute.
The variable defined by Filter Var can be referred in the collection attribute Filter. The value of
these variables can be accessed from anywhere while evaluating the current collection objects.
The variable defined using ParmVar can be referred by any attribute within the collection

Source Var
The attribute Source Var evaluates the value based on the source object.
Syntax
Source Var : <Variable Name> : <Data Type> : <Formula>
Where,
<Variable Name> is name of variable
<Data Type> is the data type of the variable
<Formula> can be an expression formula which evaluates to value of the variable
Example:
The requirement here is to calculate the Date and VoucherType wise ledger total amounts
[Collection : Src Vouchers]
Type : Voucher
Fetch: Date, VoucherNumber, VoucherTypeName, AllLedgerEntries.*

[Collection : Summary Collections]


Source Collection : Src Vouchers
Source Var : SrcVch: String: $Date +”/”+$VoucherTypeName
Walk : AllLedgerEntries
By : VchDateType: ## SrcVch
By : LedName: $LedgerName
Aggr Compute: TotValForLed: Sum: $Amount

248
Objects, Collections & Internal Object Structure

In the above example a variable SrcVch is created which concatenates Date and Voucher Type
from the Source Objects. Then the objects are grouped first based on the SrcVch and then by
Ledger name. The aggregation is applied on the ledger amount.

Compute Var
The attribute Compute Var evaluates the value of based on the Current Objects i.e., on the
basis of the objects obtained after evaluating the Walk specification.
Syntax
Compute Var : <Variable Name> : <Data Type> : <Formula>
Where,
<Variable Name> is name of variable.
<Data Type> is the data type of the variable.
<Formula> can be an expression formula which evaluates to value of the variable

Example:
The only difference in this example from the previous one is that if the source objects contain
Sale as Voucher type then the second level grouping will be on the basis of combination of
Date, VoucherType and ledger name in combination.

[Collection : Summary Collections]


Source Collection : Src Vouchers
Source Var : SrcVch: String: $Date +”/”+$VoucherTypeName
Walk : AllLedgerEntries
Compute Var : ComputeVch: String: If ##SrcVch contains+
“Sale” Then $LedgerName + “-“+ ##SrcVch +
Else $LedgerName
By : VchDateType : ## SrcVch
By : LedName : ## ComputeVch
Aggr Compute : TotValForLed: Sum: $Amount

Filter Var
The attribute Filter Var evaluates the value of the variable on Aggregate Objects ie the objects
obtained in collection after the grouping criteria and aggregation is applied.

249
Objects, Collections & Internal Object Structure

Syntax
Filter Var : <Variable Name> : <Data Type> : <Formula>
Where,
<Variable Name> is the name of variable
<Data Type> is the data type of the variable
<Formula> can be an expression which evaluates to value of the variable type

Example:
In the example we require to filter those item for which the aggregated billed qty is greater
than zero.
[Collection: SCF CFBK Voucher]
Type : Voucher
Filter : SCF IsSalesVT
;; Cmp Var is used in the above Filter
Compute Var: Compute Var in Source: Logical: $IsSales:+
$VoucherTypeName
Fetch : VoucherTypeName, VoucherNumber

[Collection: SCF Smp Stock Item]


Source Collection: SCF CFBK Voucher
Source Var: Src Var: String: $Date + "-" + $VoucherTypeName
Walk : Inventory Entries
/* If the Source Variable Src Var contains "12", then IName Variable stores only Stock Item Name method else Stock Item Name +
value of the variable Src Var The grouping is finally done on the resultant value */

Compute Var: IName : String: If ##SrcVar contains "12" then+


$StockItemName else $StockItemName + "-" + +
##SrcVar
By: IName : ##IName
Aggr Compute : BilledQty: SUM: $BilledQty
;; The following Filter var retains a logical value if method BilledQty is greater than 100 used in Filtering Final Object

Filter Var: Fil Var : Logical: $$Number:$BilledQty > 100


Filter : Final Filter

250
Objects, Collections & Internal Object Structure

[System: Formula]
SCF IsSalesVT: ##ComputeVarinSource
Final Filter : ##FilVar

Parm Var
Collection Artifact evaluates the various attributes either during initialization or at the time of
gathering the collection. It may require various inputs from the Requestor context.
For e.g., the evaluation of ‘Child of’ and ‘Filter’ attribute happens at the time of gathering the
collection. It requires certain values from Requestors context like $Name. In filter attribute if
$Name of each object is to be compared with $Name of the Requestors context then we have
to refer it as $ReqObject:$Name. However, in a Remote Environment where the Requestor
Context is not available within the collection at the Server side. Hence we require attribute
Parm Var. This variable is a context free structure in the collection. The variable is evaluated
only once in the context of the caller/requestor. This happens at collection initialization and
the expression provided to it is evaluated and further stored as a variable which can be referred
within any of the attributes of the collection at any given time. This is made available at the
Server end by passing it with the XML Request.
Syntax
Parm Var : <Variable Name> : <Data Type> : <Formula>

Where,
<Variable Name> is the name of variable
<Data Type> is the data type of the variable
<Formula> can be an expression which evaluates to value of the variable data type
In the code given below the Line Groups and Ledgers is repeating on a Group collection. From
within that line a part is exploded which displays the List of Ledgers belonging to that Group.
The line List of Ledgers within this part Repeats on the collection Smp List of Ledgers
[Part: Groups and Ledgers]
Lines : Groups and Ledgers
Repeat : Groups and Ledgers : List of Groups
Scroll : Vertical

[Line: Groups and Ledgers]


Fields : GAL Particulars
Right Fields : GAL ClosBal

251
Objects, Collections & Internal Object Structure

Explode : List of Ledgers : ##ExplodeFlag

[Part: List of Ledgers]


Lines : List of Ledgers
Repeat : List of Ledgers : Smp List of Ledgers
|
|
|
[Collection: Smp List of Ledgers]
Type : Ledger
Child Of : ##ParmLedName
Parm Var : ParmLedName : String : $Name

6.7.9 Usage as Tables


TDL allows us to display the values obtained from the collection as a pop-up list. This pop-up
list is knows as Table. At Field definition, ‘Table’ attribute is used for populating Objects of a
collection as a Table.

Field Attribute –Table


Syntax
Table : <Collection Name>, <Collection Name>, …

Where,
<Collection Name> is the name of collections and can be a comma separated list
Example:
List of ledgers to be displayed as a table within the field for selection
[Field : Sample Field]
Table : LedgerCollection

[Collection : LedgerCollection]
Type : Ledger

252
Objects, Collections & Internal Object Structure

Collection Attribute – Table


In order to display a collection as a Table the attribute Format is mandatory. This attribute is
used to specify the methods and corresponding width as it appears in the Table.
Syntax
Format : <Method Name> : <Width>
Example:
[Field : Sample Field]
Table : LedgerCollection
[Collection : LedgerCollection]
Type : Ledger
Format : $Name, 15
Format : $Opening Balance, 20

Collection Attribute –Title & Sub Title


The attribute Title is used to display a title for the Table. SubTitle attribute can be used to
display individual titles for the columns of the Table

Syntax
Title : <String >
SubTitle : <List of comma separated string>
Example:
[Collection: Ledger Collection]
Type : Ledger
Format : $Name, 15
Format : $OpeningBalance, 10
Title : $$LocaleString:"Table Sub-Titles"
Sub Title : $$LocaleString:"Name"
Sub Title : $$LocaleString:"Op.Balance"

The above code example displays a table with two columns. Column titles are also displayed
with the help of attribute Sub Title. Instead of specifying the Sub Title attribute multiple times
a comma separated list can be given as shown like :
Sub Title : $$LocaleString:"Name", $$LocaleString:"Op.Balance"

253
Objects, Collections & Internal Object Structure

We have already seen that it is possible to populate a collection either by using an Internal
Object or an External Object which can also be a Dynamic Object populated from a variety of
Data Sources like HTTP/HTTPS-XML/DLL/ODBC etc. The various types of Collections
which can be displayed as tables are listed as below .
 Voucher Collection
 ODBC Collection
 XML Collection
 Summary/Aggregate Collection
 DLL Collection
 Variable Collection
$$Table
$$Table returns the corresponding method value selected from the table which mentioned in
the field using the field value
Syntax
$$Table:<FieldName>:<Expression>
In the example given below, let us assume that the field Led Name Field has a table. Based on
selection of the Ledger Name, Ledger Opening should be picked automatically in Opening
Bal Field.
[Field: Opening Bal Field]
Set As : $$Table:LedNameField:$OpeningBalance
In the above Field, the Opening Balance Method from Object Ledger is set at the current field
by using Table Function.

Exercise 6.7
Objective
The objective of this program is to open a report in Alter Mode and a Table is displayed. On
selecting an Item, the corresponding Description is set in the subsequent Field using Function
'Table'.
Capabilities Used
 Table attribute at Field definition to display pop up list
 At Set As of the Field used Function $$Table to set corresponding values in the sub-
sequent field
 Attributes Type, Title, Format and Subtitle has been utilized for deciding the Object
Type, Title to be displayed for the pop up list, Values in the columns of the pop up
list, Title for the columns respectively

254
Objects, Collections & Internal Object Structure

Code
[Report: Exer Collection as Table]
Form : Exer Collection as Table
Title : "Collection as Table"

[Form: Exer Collection as Table]


Parts : Form SubTitle, Exer Collection as Table
Local : Field: Form SubTitle: Info: +
"Usage of Collection as Table"
[Part: Exer Collection as Table]
Lines : Exer Collection as Table

[Line: Exer Collection as Table]


Fields : Medium Prompt, Name Field, Short Name Field
Local : Field: Medium Prompt: Info: "Select an Item :"
Local : Field: Name Field : Table : Exer Cat List of Stock Items
Local : Field: Name Field : Show Table: Always
/*Function 'Table' extracts the method value 'Description' of the selected Item from the table in the Field 'NameField'.*/
Local : Field: Short Name Field: Set As: $$Table:+
NameField:$Description
Local : Field: Short Name Field: Set Always: Yes
Local : Field: Short Name Field: Full Width: Yes
/* Collection Attribute 'Format' displays the required Methods to be displayed in the Table */
Format : $Name
Format : $Parent
Format : $Description, 30
Format : $ClosingBalance, 20
/*Collection Attribute 'SubTitle' displays the SubTitle of the required Methods displayed using Format. The order of the
'SubTitle' must match the order of the 'Format'.*/
SubTitle: "Stock Item Name", "Stock Group"
SubTitle: "Description", "Closing Balance"
;;End-of-File

255
Objects, Collections & Internal Object Structure

Output

The report has three fields. Field Medium Prompt has been used to display Label Select an
Item”. Field ‘Name Field’ is where we have displayed the pop up list. Attribute Table has been
used and the name of the collection ‘Exer CaT List of Stock Items’ has been provided as the
attribute value.
The collection is holding Object of Type Stock Item. Attribute Title has been used to provide
title to the Table. Attribute Format would decide the values to be displayed in the column.
Give format as many columns you require in your Table. Format attribute takes one value as
parameter. This can be any formula and we can provide width to the column by providing a
comma after the formula i.e., Format: $ClosingBalance, 20. Attribute Sub title helps us to
provide the Title for the columns. The width for this would be picked from the corresponding
Format attribute.
At field Short Name Field we would like to display description of the Stock Item which has
been selected in the previous field, hence we have made use of $$Table function at Set As.
Function $$Table accepts two parameters. First parameter is the name of the field to which
Table is attached and second parameter is the corresponding method which is to be selected
based on the object selected from the Table.

6.7.10 Dynamic Table Support using Unique Attribute


The Unique attribute of Collection definition is used to control the display of unique values in
the table for a specified method based on values selected from the table previously in a field.
The display of values is changed dynamically based on the field value.
Syntax
Unique : <Table Object Method>[,<Field Object Method>+
[,<Extended method>]]

256
Objects, Collections & Internal Object Structure

Where ,
<Table Object Method> is a method whose value is uniquely displayed in the table.
<Field Object Method> is the storage/method which is associated with the field which is
used to control the display of Table values dynamically. If a particular table object method
value from the Table is selected in the field, then that value is removed from the table based on
the value of <Field Object Method> This parameter is mandatory if extended method is
specified else its optional.
<Extended Method> is a storage/method whose value specifies whether the previous value of
field object method should be used to control unique values display in the table. If the current
value of the value of <Extended Method> is same as that of previous values then <Field
Object Method> value is considered while populating unique value in the table. Otherwise
the <Field Object Method> value is ignored to set the unique values in the table. This
parameter is optional.
The collection and definition is modified as follows so that while populating unique values of
Batch names in the table, Stock Item name is also considered apart from the value of the field
storage/ method BtName. i.e., if the same stock item is selected in the field which has been
selected previously then the field storage/method value BtName is considered for controlling
display of Batches else it is ignored.
Example:
[Part: StkBat]
Repeat : GrpLedLn: StkItemColl

[Line : GrpLedNm]
Field : StkIt, StkBatNm

[Field : StkIt]
Use : Name Field
Storage: ItemName

[Field : StkBatNm]
Use : Name Field
Table : BatList
Storage : BtName
Show Table : Always
Dynamic : Yes

257
Objects, Collections & Internal Object Structure

[Collection: BatList]
Title : “List of Batches”
Type : Batch
Format : $BatchName,20
Child of : #StkIt
Unique : $BatchName,$BtName,$ItemName
Here the method $Itemname used in the unique attribute is the storage defined in the field
‘StkIt’. Consider the following Scenario:
Stock Item Name Batch Name
Batch A
Item 1 Batch B
Batch C
Batch A
Item 2 Batch B
Batch C
Batch A
Item 3 Batch B
Batch C
There are two fields in the line one which displays stock item name and the other displays
batches. The selected batch is stored in the UDF say BtName. The following table displays the
values in each field and the unique values in the tables based on the selection.
Line No Value in Field 1 Values in Selected Value
Table in Field 2
1 Item 1 Batch A Batch A
Batch B
Batch C
Primary Batch

258
Objects, Collections & Internal Object Structure

2 Item 2 Batch A Batch B


Batch C
Primary Batch
3 Item 1 Batch B Batch C
Batch C
Primary Batch

6.7.11 Collection Functions-Data Retrieval & Filtering


Till the last topic we have concentrated on data retrieval and filtering of data using the various
attributes available in the Collection. We will now discuss the various functions available
which will be useful in specifying the data and apply filters as required for retrieving the data
from the collection

$$NumItems
$$NumItems returns the count of Objects in the given collection.
Syntax
$$NumItems:<CollectionName>
Where,
<CollectionName> is the name of a Collection
Example:
[Field : Sample Field]
Set as : $$NumItems:Ledgers
[Collection : Ledgers]
Type : Ledger

$$FullList
$$FullList returns a list of comma separated values of the specified expression evaluated for
each object of the collection.
Syntax
$$FullList:<CollectionName>:<Expression>
Where,
<CollectionName> is the name of the Collection
<Expression> refers to any valid expression to be evaluated on each Object of the Collection

259
Objects, Collections & Internal Object Structure

Example:
[Field : Sample Field]
Set as : $$FullList:Address:$Address
$$FullListEx
$$FullList returns a list of values of the specified expression evaluated for each object of the
collection separated by the character as specified.
Syntax
$$FullListEx:<separator character>:<CollectionName>:+
<MethodFormula>
Example:
[Field : MyAddField]
Set as : $$FullListEx:”;”:CompanyAddress:$Address

$$CollectionField
$$CollectionField is used to retrieve the value of a specified expression from the specified
Object of a Collection. In other words, the Function CollectionField extracts the required
expression value from the object at a specified index within the given Collection
Syntax
$$CollectionField:<ValueExpression>:<Index>:<CollectionName>
Where,
<ValueExpression> refers to any valid expression to be evaluated on the specified Object of
the Collection
<Index> denotes the position
<CollectionName> is the name of the Collection

Example:
[Field : Sample Field]
Set as : $$CollectionField:$Amount:1:AllLedgerEntries
The example returns the Amount from the first object of AllLedgerEntries available within the
current Voucher Object.

$$CollectionFieldByKey
The function $$CollectionFieldByKey is used to retrieve values from a collection based on the
key specified.

260
Objects, Collections & Internal Object Structure

Syntax
$$CollectionFieldByKey:<Method Name>:<Key Formula>:<Collection
Name>
Where,
<Method Name> is the name of the method
<Key Formula> is a formula that can be mapped to the methods in the current context as
defined in the search key
<Collection Name> is the collection name in which the Objects are available with their
unique Keys as identifiers

The Search key specifications and detailed examples have already been taken
up in the prior sections

$$CollAmtTotal
$$CollAmtTotal is used to calculate the total of all the values of the expression evaluated for
each Object of the collection. The expression needs to evaluate to a value of Amount
Datatype.
Syntax
$$CollAmtTotal:<CollectionName>:<ValueExpression>
Where,
<CollectionName> is the name of a Collection
<ValueExpression> is any valid TDL expression to be evaluated on each Object in the Col-
lection.
Example:
[Field : Sample Field]
Set As : $$CollAmtTotal:LedgerEntries:$Amount
The above example calculates the total of method Amount for all objects of the Ledger Entries
Object available within the current Voucher Object

$$CollNumTotal
$$CollNumTotal is used to calculate the total of all the values of the expression evaluated for
each Object of the collection. The expression needs to evaluate to a value of Number
Datatype.

261
Objects, Collections & Internal Object Structure

Syntax
$$CollNumTotal:<CollectionName>:<ValueExpression>
Where,
<CollectionName> is the name of a Collection
<ValueExpression> This refers to any valid expression to be evaluated on each Object of the
Collection
Example:
[Field : Sample Field]
Set as : $$CollNumTotal:InventoryEntries:$Height
The above example calculates the total of method height(external method) for all objects of
the InventoryEntries Object available within the current Voucher Object

$$CollQtyTotal
$$CollQtyTotal is used to calculate the total of all the values of the expression evaluated for
each Object of the collection. The expression needs to evaluate to a value of Quantity
Datatype.
Syntax
$$CollQtyTotal:<CollectionName>:<ValueExpression>
Where,
<CollectionName> is the name of a Collection
<ValueExpression> refers to any valid TDL expression to be evaluated on each Object of the
Collection.

Example:
[Field : Sample Field]
Set as : $$CollQtyTotal:InventoryEntries:$BilledQty
The above example calculates the total of method BilledQty for all objects of the InventoryEn-
tries Object available within the current Voucher Object

$$FilterCount
$$FilterCount is used to get the total number of Objects in a Collection after the specified filter
is applied.

Syntax
$$FilterCount:<CollectionName>:<FilterExpression>

262
Objects, Collections & Internal Object Structure

Where,
<CollectionName> is the name of a Collection
<FilterExpression> is a System Formula
Example:
[Field : Sample Field]
Set as : if @PartyLedAvailable then “Supplier” else +
“ -- No Party --”
PartyLedAvailable : $$FilterCount:AllLedgerEntries:+
IsPartyLedgerAccount > 1
[System: Formula]
IsPartyLedgerAccount: $IsPartyLedger
The filter in the example, checks whether Ledger Name is a Party Ledger Name or not. In case
it returns true for more than 1, then the field would display Supplier, else it would display “ --
No Party --”

$$FilterValue
$$FilterValue is used to get the value of a specified expression based on the position specified
within the set of objects returned after filter condition is applied.
Syntax
$$FilterValue:<ValueExpression>:<CollectionName>:<Index>:<Fil-
terExpression>
Where,
<CollectionName> is the name of the Collection.
<FilterExpression> is used to specify the filter condition.
<Index> denotes the position.
<ValueExpression> refers to any valid expression to be evaluated on each Object of the Col-
lection.
Example:
[Field : Sample Field]
Set as : $$FilterValue:$LedgerName:LedgerEntries:First:+
IsPartyLedger
The example retrieves the method $LedgerName from the first LedgerEntries Object which
satisfies the filter condition IsPartyLedger

263
Objects, Collections & Internal Object Structure

$$FilterQtyTotal
$$FilterQtyTotal is used to calculate the total of all the values of the expression evaluated for
each Object of the collection which satisfies the Filter condition. The expression needs to
evaluate to a value of Quantity Datatype.
Syntax
$$FilterQtyTotal:<CollectionName>:<FilterExpression>:+
<ValueExpression>
Where,
<CollectionName> is the name of a Collection
<FilterExpression> is a System Formula. The Filter Expression is evaluated for each Object
and the resultant Objects that clear the filter are selected for further processing.
<ValueExpression> refers to any valid expression to be evaluated on each Object of the Col-
lection.
Example:
[Field : Sample Field]
Set as : $$FilterQtyTotal:InventoryEntries:IName:$BilledQty
[System : Formula]
IName : $StockItemName = “Tally ERP 9”

The above example calculates the total of method BilledQty for all objects of the InventoryEn-
tries where the StockItemName is “Tally.ERP 9”available within the current Voucher Object

$$FilterAmtTotal
$$FilterAmountTotal is used to calculate the total of all the values of the expression evaluated
for each Object of the collection which satisfies the Filter condition. The expression needs to
evaluate to a value of Amount Datatype.
Syntax
$$FilterAmtTotal:<CollectionName>:<FilterExpression>:+
<ValueExpression>
Where,
<CollectionName> is the name of a Collection
<FilterExpression> is a System Formula. Filter Expression is evaluated for each Object and
the resultant Objects that clear the filter are selected for further processing
<ValueExpression> is any valid expression to be evaluated on each Object of the Collection

264
Objects, Collections & Internal Object Structure

Example:
[Field : Sample Field]
Set As : $$FilterAmtTotal:AllLedgerEntries:CashBankEntries:$Amount
[System :Formula]
CashBankEntries :($$IsCashLedger:$LedgerName) AND ($$IsDr:$Amount)
The above example calculates the total of method Amount for all objects of the AllLedgerEn-
tries where Ledger Name is a CashLedger and Amount is a debit amount available within the
current Voucher Object

6.7.12 Voucher Object Structure


Let us understand the structure of Voucher which is one of the most commonly used Internal
Object for majority of customization purposes. We will discuss the variations in Voucher
Object structure based on different Voucher Types.

Accounting Voucher
Vouchers in which only Account masters are used are termed as ‘Accounting Voucher’.
Receipt Voucher and Payment Voucher fall under this category.
As depicted in the above pictorial representation, Voucher Object is the Primary Object. All
Ledger Entries is the sub collection under Voucher Object which contains Sub Object ’Ledger
Entry’. Bill Allocations is a sub collection under Ledger Entry Object which contains ‘Sub
Object Bill Allocations’

265
Objects, Collections & Internal Object Structure

Inventory Voucher
Vouchers in which only inventory masters are used are termed as ‘Inventory Voucher’. Stock
Journal Voucher falls under this category.
As depicted in the above pictorial representation, Voucher Object is the Primary Object.
Inventory Entries In and Inventory Entries Out are the sub collection under Voucher Object
which contains Sub Object ’Inventory Entry’ respectively. Each of the Inventory Entry Object
may have Batch Allocations sub collection which contains ‘Batch Allocations’ sub object.

Accounting cum Inventory Voucher


Vouchers in which accounting masters as well as inventory masters are used are termed as
‘Accounting cum Inventory Voucher’. Sales Voucher and Purchase Voucher fall under this
category. There is a difference in the Voucher Object structure based on whether it is entered
as ‘A Voucher’ or ‘Invoice’

266
Objects, Collections & Internal Object Structure

As Voucher
Voucher is the traditional way of entering data. Debit and Credit is used to enter data. As
depicted in the above pictorial representation, Voucher Object is the Primary Object. Bill Allo-
cations, Interest Collection, Inventory Allocations and Category Allocations are the sub col-
lection under Voucher Object which contains Sub Object Bill Allocations, Vch Interest
Collection, Inventory Entry and Category Allocations respectively. Inventory Entry sub
Object may have sub collection Batch Allocations which contains Batch Allocations sub
object. Category Allocations sub object may have sub collection Cost Centre Allocations
which contains Cost Center Allocations.

267
Objects, Collections & Internal Object Structure

As Invoice
As Invoice is the most widely used format in Tally where Tally helps in various calculations.
While entering a Sales Invoice, all the duty and Tax calculations are done automatically. Also
Voucher Classes can be used only with As Invoice Format. While entering in Invoice Mode,
the Voucher Object Structure is as shown below:

Detailed hierarchy and schema reference of the various Internal Objects can be
referred to from the Schema Brow

268
Chapter 7: Action, Event Framework
and Key Definition

7.1 Action Framework


In the previous chapter, we have covered the concept of Objects & Collections in TDL and
discussed the structure of the most widely used Internal Data Object structure i. e the Voucher
Object.
As we already know that, TDL is basically a non-procedural/Action driven language which
allows the programmer to specify the actions required to perform a task. The sequence in which
these Actions get triggered is purely based on user interaction or on the basis of occurrence of
an event. These Actions in turn act upon a particular definition.
In this chapter, we will begin our discussion by understanding the meaning of an Action and the
various types of Actions available. As we progress, we will have a detailed conceptual under-
standing on Action invocation, evaluation process and then conclude with listing and usage of
various widely used Actions and Events available in TDL.
7.1.1 Understanding Actions
Action can be defined as ‘the state or process of acting or doing’. Actions are activators of
specific functions with a definite result.
In TDL, whenever an event occurs an Action or a sequence of Actions can be initiated. The
events can be broadly classified as
User Driven
While operating on the application, the user may press a key, click on a button or select a par-
ticular menu item. These events require explicit user interaction. Whenever such User Driven
events occur some Actions can be invoked.
System Driven
There are certain events, which occur implicitly and do not require user intervention for e. g
when the application starts, when it is ending, on saving of a form or an invoice is getting
printed. Actions can also be invoked on occurrence of such System Driven Events.

269
Action, Event Framework and Key Definition

This can be clearly understood with the pictorial representation as given below:

The Actions which gets triggered on the particular event occurrence can be of two types:
 Predefined Actions
These actions are provided by the platform and can be triggered by using the specific keyword
provided for it.
 User defined Actions
These are the Actions which can be defined by the programmer. The TDL procedural artifact
Function can be used to create such actions where the programmer has a complete control on
the desired functionality required.

270
Action, Event Framework and Key Definition

Here we will only concentrate on how to invoke a User Defined Function.


Creation and usage will be taken up in detail in the subsequent chapter “TDL
Procedural”

There is a difference in the manner in which a Predefined Action and a User Defined Action is
invoked.
7.1.2 Invoking Predefined Actions
In TDL, action has an action keyword. Display, Line Down, Form Accept etc. are the action
keywords. Some of the actions accept parameters and some do not.
Syntax
Action: Action Name [: Action Parameters]
In the above syntax:
 Action is the keyword
 Action Name specifies the name of the action to be performed. It can be any of the
predefined actions. Eg: Display, Print etc.
 Action Parameters are set of parameters which are to be passed to the Action as
required
Example:
1. Action : Print Report
This actions prints the current report in context unless explicitly specified

2. Action : Create : Sample Report


The report Sample Report is opened in create mode using the action Create. It takes the
parameters as Report Name
Example of Predefined Actions
Let us learn how to use predefined actions in our TDL
Exercise 7.1
Objective
The objective of this program is to demonstrate the usage of predefined actions in TDL. To
print the default report Balance Sheet.
Capabilities Used
 Usage of the action Print
 Modification of the menu Gateway of Tally

271
Action, Event Framework and Key Definition

Code
[#Menu: Gateway of Tally]

Key Item: "Invoking Predefined Actions": P: Print: Balance Sheet

Output

272
Action, Event Framework and Key Definition

Program Explanation
The above output shows the print preview of Balance sheet. It displayed by using the action
Print. When you select the menu item Invoking Predefined action, it will display the print con-
figuration screen to print the Balance sheet report. When you accept the screen, it displays the
print preview of Balance sheet.

7.1.3 Invoking User Defined Actions


Invocation of a User Defined Action created using Function requires CALL keyword.
Syntax
Action: CALL : <Function Name>[: Function Parameters]
Example:
Action : CALL : List Fill Value
In the example the action List Fill Value is invoked which is defined using a function defini-
tion. The sample function definition is give as below

[Function: List Fill Value]


Variable : Counter: Number
00: WALK COLLECTION: Group
01: INCREMENT: Counter
02: LIST ADD : List Var : ##Counter : $Name
03: END WALK

Example of User Defined Actions


Let us learn how to define and use the Actions
Exercise 7.2
Objective
The objective of this program is to demonstrate the definition and usage of user-defined
actions create using Function definition. This Function executes all the actions listed by the
programmer sequentially.
Capabilities Used
 The Action CALL to invoke the user defined actions
 User Defined Function
 The Action Print inside the function
 SET attribute at Function definition

273
Action, Event Framework and Key Definition

Code
[Menu : Exer Action Event Framework and Key definition]
Key Item : "Invoking Predefined Actions": P: Print: Balance Sheet
Key Item : "Invoking User defined Actions": U : CALL :+
Exer Invoking User Defined Action

[Function: Exer Invoking User Defined Action]


;; Locally declaring the required Variables
Variable: DSPShowClosing, ExplodeFlag, ExplodeAllLevels:+
Logical
;; Required Actions are being pre-defined such that all the actions get executed sequentially/procedurally
00 : MSGBOX: "User Defined Action": "This will print the +
Final Accounts"
;; Enabling the required variables
10 : SET : DSPShowClosing: Yes
20 : SET : ExplodeFlag : Yes
30 : SET : ExplodeAllLevels: Yes
;; Printing Final Accounts with above set values
40 : PRINT : Trial Balance
50 : PRINT : Profit and Loss
60 : PRINT : Balance Sheet
;; End-of-File

274
Action, Event Framework and Key Definition

Output

275
Action, Event Framework and Key Definition

276
Action, Event Framework and Key Definition

277
Action, Event Framework and Key Definition

Program Explanation
For the above outputs are for Function Exer Invoking User Defined Action is invoked from
the menu item Exer Action Event Framework and Key definition itself. This is to print the
default reports like Trial Balance, Profit & Loss A/c, and Balance Sheet. Inside the function
MSGBOX is used to display the message This will print the Final Accounts to the user,
before invoking the above Print reports. The action Print is used for the same.
The SET attribute is used to set the value Yes for the variables DSPShowClosing, Explode-
Flag, ExplodeAllLevels. Based on this variable values the final accounts were printed.
7.2 Action Association
As we have already seen that, an Action can be triggered on the occurrence of either an User
Driven/System Driven Event. An User driven Event can be identified by defining a Key,
Button or a Menu Item. For identifying System Driven Event we have a predefined set of
Events available in TDL. These can either be specified at System level or at a particular defini-
tion level for which it is provided.
For handling User Driven Events the Action can be associated at
 Key/Button Definition using the Action attribute
 Menu Definition along with a Menu Item
 Field Definition using the Action keyword
For handling System Driven Events the Action can be associated at
 System: Event definition using the Event keyword provided
 Specific definition level using the On attribute and Event Keyword
7.2.1 Action Association at Button/Key Definition
An Action can be triggered from a Button/Key definition by specifying the particular Action
using the attribute Action. The parameters to be supplied to the Action as required.
Syntax
[Button: Button Name]
Action: Action Keyword [: <Action Parameters>]
Where:
The Action Keyword can be any Global or Object Specific Action
The Action Parameter is as required by the Action Keyword. If the Action Keyword is
Menu, then the Action Parameter necessarily has to be a Menu Name, else if action name is
Create, Alter, Display then the action parameter should be a Report Name.
Example:1
Actions with Parameters
[Button: Outstandings]
Key : F5

278
Action, Event Framework and Key Definition

Action : Menu: Outstandings


[Button: Trial Balance]
Key : F6
Action : Display: Trial Balance
Action Menu requires a Menu Name as a Parameter and Actions Create, Display, Alter require
a Report Name as a Parameter.
Example:2
Actions without Parameters
[Button: Printing Button]
Action : Print Report
[Button: Exporting Button]
Action : Export Report
Action Parameters for the Actions, Print Report and Export Report is not mandatory. If the
Action Parameter is specified, then it prints the specified Report else it prints the current
Report in context.

7.2.2 Action Association at Menu Definition


Action Association at Menu Definition is done through the Menu Item. Every Menu Item
except Quit is associated with an Action. If an Item is added without any action, then the
default action associated is to exit from the current Menu.
Syntax
[Menu: Menu Name]
Add : Key Item: [Position] : Display Item : Unique Key :+
Action Keyword : <Action Parameter>
Where,
Action Keyword can be any Global Action
The Action Parameter is as required by the Action Keyword. If the Action Keyword is
Menu, then the Action Parameter necessarily has to be a Menu Name, else if action name is
Create, Alter, Display then the action parameter should be a Report Name.

Example
[Menu: Commonly Used Reports]
Add: Key Item: Trial Balance: T: Display : Trial Balance
Add: Key Item: At Beginning: Outstandings: O: Menu : Outstandings

279
Action, Event Framework and Key Definition

In the above example, a Menu Commonly Used Reports is defined with two Items, viz.,
 An Item Trial Balance is added displaying default report Trial Balance. Here, the
Action is Display and the Action parameter has to be a Report Name.
 An Item Outstandings is added at the beginning to activate another Menu Outstand-
ings. The Action here is a Menu, so the Action Value required is a Menu Name.
Here ‘At Beginning’ is the value of position and ‘Outstandings’ is the display item
an ‘O’ is the unique key.
7.2.3 Action Association at Field Definition
Action Association at Field definition is done using the Action Keyword with the parameters
and the optional condition
Syntax
[Field: Field Name]
Action Keyword: Action Parameters [:< Condition >]
Where,
Action Keyword can be both, Global or Object Specific Actions
Action Parameters can be the Value on which these Actions could be performed
<Condition> is optional. This restricts the action to perform only if the Condition returns true
Example:
[Field: My Trial Balance]
Display : Group : $$IsGroup
Display : Ledger: $$IsLedger

In the example above, the Field Trial Balance has two statements, viz,
 Displaying a Group if the current object in context is a Group
 Displaying a Ledger if the current object in context is a Ledger
Typically, actions initiated through the selection of a Menu item or through an assignment to a
Key or a Button.

Example for Action association at Field


Let us try to understand the action association at Field level
Exercise 7.3
Objective
The objective of this program is to understand the Action Association at Field. This code helps
us achieve the Drill Down behavior where on hitting an Enter from one Ledger, it moves to the
Ledger Vouchers of that ledger.

280
Action, Event Framework and Key Definition

Capabilities used
 Action usage at Field level
 Button & Key usage
 Filter usage at collection level
 Repeat attribute at part level to repeat the line over collection

Code
[Report: Exer Action Association at Field]
Form : Exer Action Association at Field
Title : "Object Association at Field"

[Form: Exer Action Association at Field]


Buttons : F2ChangePeriod
Keys : ChangePeriod
Parts : Form SubTitle, Exer Action Association at Field
Local : Field: Form SubTitle: Info: "Object Association+
at Field"
[Part: Exer Action Association at Field]
Lines : Exer AAF Title, Exer AAF Details
Repeat : Exer AAF Details: Exer AAF VchSummColl
Scroll : Vertical
CommonBorder : Yes

[Line: Exer AAF Title]


Use : Exer AAF Details
Local: Field: Default: Type: String
Local: Field: Default: Align : Center
Local: Field: Default: Style : Normal Bold
Local: Field: Default: Lines : 0
Local: Field: Exer AAF PartyName: Set As: "Party Name"
Local: Field: Exer AAF PartyAmt: Set As: "Nett Transacted Amount"
Border : Thin Top Bottom

281
Action, Event Framework and Key Definition

[Line: Exer AAF Details]


Fields : Exer AAF PartyName
Right Fields: Exer AAF PartyAmt
Local: Field: Default: Style: Normal

[Field: Exer AAF PartyName]


Use : Name Field
Set As : $ExerAAFLedgerName
FullWidth: Yes
/* Action 'Display' is triggered from Field when an Enter is pressed on the current Field and the default report 'Ledg-
erVouchers' is being displayed.*/
Display : LedgerVouchers
;; Default Report 'LedgerVouchers' displays the Vouchers of a particular Ledger stored in the Variable 'LedgerName'
Variable : LedgerName
[Field: Exer AAF PartyAmt]
Use : Amount Field
Set As : $ExerAAFLedgerAmt
Border : Thin Left
Format : "DrCr"
Width : 15% Page

[Collection: Exer AAF VchColl]


Type : Voucher
Filter : Exer AAF NonEmptyLedgers

[Collection: Exer AAF VchSummColl]


Source Collection: Exer AAF VchColl
By : Exer AAF LedgerName: $LedgerEntries[1].LedgerName
Aggr Compute : Exer AAF LedgerAmt: Sum: $LedgerEntries[1].Amount
Filter : Exer AAF NonEmptyAmt

282
Action, Event Framework and Key Definition

[System: Formula]
Exer AAF NonEmptyLedgers: $$NumItems:LedgerEntries > 0
Exer AAF NonEmptyAmt : NOT $$IsEmpty:$ExerAAFLedgerAmt
;; End-of-File

Output

283
Action, Event Framework and Key Definition

284
Action, Event Framework and Key Definition

Program Explanation
This is to demonstrate the action association at field level. Action display is called from the
field Exer AAF PartyName. Inside the part Exer Action Association at Field the line Exer
AAF Details is getting repeated over the collection Exer AAF VchSummColl and this col-
lection holds the details about Ledgers.
Exer AAF LedgerName, Exer AAF LedgerAmt are the two methods which holds Ledger-
name and Ledger Amount respectively. The Fields Exer AAF PartyName, Exer AAF
PartyAmt were used to display the party name and Amount. The action Display is triggered
from the Field Exer AAF PartyName when an Enter is pressed on the current Field and the
default report 'LedgerVouchers' is being displayed. This report displays the vouchers of par-
ticular ledger stored in the variable called LedgerName.
7.2.4 Action Association at System Event Definition
System events are events for which no object context is available when they occur. Eg., Tally
application launch. An Action can be associated on occurrence of such an event by specifying
it within the System :Event definition.

285
Action, Event Framework and Key Definition

Syntax
[System: Events]
Label : EventKeyword : ConditionExpr : ActionKeyword :+
Action Parameters
Where,
<Label> is name assigned to the event handler. This has to be unique for each event handler.
<EventKeyword> can be any one of System Start, System End, Load Company, Close
Company.
<ConditionExpr> should return a logical value and the action will be performed only if the
condition returns TRUE
<ActionKeyword> is the Action which is to be triggered
<Action Parameters> parameters of the actions specified
Example:
[System: Events]
AppStart1: System Start : TRUE : CALL : MyAppStart
The function ‘MyAppstart’ is called as soon as Tally application is launched.
7.2.5 Action Association for Object Specific Events
The events that are performed only if the specific object context is available are referred as
Object Specific events. The Action can be specified on the occurrence of such an event by
using the ON attribute at the specific interface object definition level.
Syntax
ON : EventKeyword : ConditionExpr : ActionKeyword : +
Action Parameters
Where,
<EventKeyword> can be any one of Focus, Form Accept, Before Print and After Print
<ConditionExpr> should return a logical value
<ActionKeyword> is the Action which is to be triggered
<Action Parameters> parameters of the actions specified.
ON is a list type attribute, so list of actions can be executed sequentially when the specific
event occurs.
Example:
[Form : TestForm]
On :FormAccept :Yes :HttpPost :@@SCURL :ASCII :SCPostNewIssue : +
SC NewIssueResp

286
Action, Event Framework and Key Definition

The action Http Post is executed when the event Form Accept is encountered. But the form
will not be accepted until the user explicitly calls the action Form Accept on event Form
Accept as follows:

On : FormAccept : Yes : Form Accept


If there is no events are defined in the form, then system accepts the form. Whereas when the
user overrides the event, it will only perform the actions specified by the user. So Form Accept
is used to save the object. It is also possible to specify multiple actions for the same event.
They are executed in the order specified, whenever an action execution fails then it will not
perform subsequent actions specified in the event. Now after executing the action Http Post,
Tally will execute the action Form Accept as well.

Example for Event Framework


Let us understand more about Event Framework
Exercise 7.4
Objective
The objective of this program is to understand the Action Association at Event. On entering
any value to the Field and accepting the Form, event On: Form Accept is triggered to invoke a
User Defined Function thru Action CALL.

Capabilities used
 Event On: Form Accept
 The action CALL
 Function definition and use of MSGBOX
Code
[Report: Exer Action Association at Event]
Form : Exer Action Association at Event
Title : "Action Assoication at Event"

[Form: Exer Action Association at Event]


Parts : Form SubTitle, Exer Action Association at Event
Local : Field: Form SubTitle: Info: "Action Assoication at Event"
Width : 30% Page
;; On Acceptance of this Form, this event 'On : Form Accept' is triggered and the corresponding Action i.e., Calling a
Function takes place
On : Form Accept: Yes: CALL: Exer AAE Func : #NameField

287
Action, Event Framework and Key Definition

[Part: Exer Action Association at Event]


Lines : Exer Action Association at Event

[Line: Exer Action Association at Event]


Fields : Medium Prompt, Name Field
Local : Field: Medium Prompt : Set As: "Enter any value"

[Function: Exer AAE Func]


Parameter : pInputValue: String

00: MSGBOX: "Your Input": "The entered input is " + $$NewLine +


##pInputValue
;; End-of-File

Output

288
Action, Event Framework and Key Definition

Program Explanation
The report is used to demonstrate the action association at Event. The form Exer Action
Association at Event includes On : Form Accept, when the user accepts the form Exer
Action Association at Event, it invokes the user defined function Exer AAE Func and the
input value is passing as function parameter.
The MSGBOX is used to display the message box with the accepted value.

The Event Framework will be discussed in the subsequent topics in detail where
all the events available in TDL will be taken up with relevant examples

7.3 Classification of Predefined Actions


The Predefined Actions available in TDL can be classified into System Actions and Object
Specific Actions.
System Actions are predefined actions available in default and it is not specific to any User
Interface object. E.g.,Display, Create, Alter, Print, Execute etc.
Object Specific Actions are specific to a particular User Interface Object on which it is
applied
The major difference between System Actions and Object Specific Actions are as shown in the
following table:
System Actions Object Specific Actions
Not specific to any User Interface Specific to User Interface Object
Object
Can be originated by a Menu, Button/ Can be originated by a Menu, Form, Line,
Key, Field, Function or System/ Field, Object Specific Events
Object Specific Events
Performed on the Object as specified Performed on relevant User Interface
Objects
Example: Example:
Create, Display, Alter, Print, Print Line Up, Line Down, Explode (Actions -
Report, Modify Object, Display Col- Line Object); Form Accept, Form Reject
lection, etc. (Actions - Form Object), etc

289
Action, Event Framework and Key Definition

7.4 Action Execution & Evaluation Process


Actions are executed with respect to the following contexts:
 Originator – It is an object in which the key is defined or who originated the partic-
ular action. Wherever we have defined the key, it becomes the Originator. For exam-
ple: Menu, Form, Line and Field etc.
 Executer – It is an object in which the specific action is executed, generally for
Object Specific Actions. Line Down is executed on a Line definition, so Line
becomes the executer.
Whenever the action is triggered as a result of key pressed, the process searches for the
Interface object definition in which the key is associated. The search starts from the top most
Interface object irrespective of the place from which the action originated i.e., the process
starts searching from Report object to Field object till the key association is found. The walk
through happen in the following order:

Report → Form →Part → Line → Field

While walking downward direction it only searches which Interface object has the required
key associated with it. Once the key is found it will walk backward and the action will be
performed on the object associated with action if it is object specification.
If the key is not found then the [System: Form Keys] and global keys to be searched and once
the key is found the required action will be performed.
Consider the following diagram for understanding the action evaluation sequence.

Figure 1.1 Fig: Action Evaluation Sequence

290
Action, Event Framework and Key Definition

When an event occurs it search for originator starts from Report till Field. If the same key is
defined in multiple definitions then the lowest in the hierarchy get highest priority for execu-
tion. For Object Specific Actions the search for the executer object will start from field level
and progress till report level. Once the Executer object is found the action is executed.
From the above diagram, we can infer the following
 Part, Line and Field are recursive
Forms cannot have forms

Field and Line have keys

 User can define keys and Form can have Button / Keys
 Report can have System: Form Keys or System: Menu Keys.
Example:
At field level a key is defined for event Down Arrow and action is to be performed is Form
Accept. Now the action defined can’t be performed by a field it is a Form action. So now the
field is the Originator of the action whereas the Form is the Executor object of action.
Originator Executer
The Originator originates the action The Executer executes the action associ-
by associating the Key or a Button ated with the Key or a Button initiated by
the originator
System Actions can be originated by a System Actions can be executed by the
a Menu, Button/ Key, Field, Function one which has originated the Action.
or System/Object Specific Events However, Object Specific Actions can be
whereas Object Specific Actions can executed by the Objects that have not
be originated by a Menu, Form, Line originated the Action
or a Field
The sequence followed to gather all The sequence followed to consume the
the Keys originating within a Report Keys originated is from Bottom to Top
is Top to Bottom i.e., from a Report to i.e., from a Field to a Report Definition.
a Field Definition. The lowest in the In other words, the lowest in the hierarchy
hierarchy gets the highest precedence. get the highest preference. For example, if
For example, if the same key is asso- the same key is relevant for both Part as
ciated in both Form as well as Field well as Line Definition, the Key will be
Definition, the Key at Field Definition executed in the context of the Line Defi-
will be considered for execution nition

291
Action, Event Framework and Key Definition

Example 1 Example 2
[Key: Create Ledger] [Key: Part Display PgUp]
Key : Alt + C Key : PgUp
Action : Create : Ledger Action : Part PgUp
[Field: CST Supplier Ledger] [System: Form Keys]
Key : Create Ledger Keys : Part Display PgUp
Associating the Key with the Field, Key Part Display PgUp is originated by
Field is the originator as well as Form but its executer is the Part
executer in this case

7.5 Scope of Actions


We have multi line selection capability in TDL where it is possible to select a specific set of
objects from a report. This is achieved by specifying value of Selectable attribute as Yes in the
part or line definition.
It is possible to specify scope of Actions which means the action can be performed on more
than one object based on selection. This is termed as the Scope of an Action. At present the
following Actions support scope specification
Display, Print Report, Mail Report, Export Report, Upload Report, Delete Object, Cancel
Object, Audit Object, Multi Field Set, Modify Object and in Menu Definition.
TDL allows the scope to be specified where an action is to be performed on a report, or on
current line or on selected or unselected line or all lines. This is specified using the Scope
attribute of the key/button definition
Syntax
Scope : <Scope Keyword>
<Scope keyword> takes five values Report, Selected Lines, Unselected Lines, Current Lines
and All Lines.
 The keyword Report specifies that the scope is on the object associated with the
report. The action is to be taken in the context of report object.
 The keyword Selected specifies that the action is performed only on the objects asso-
ciated with selected lines.
 The keyword Unselected specifies that the action is performed only on the objects
associated with un-selected lines.
 The keyword Current specifies that the action is performed only on the object associ-
ated with the line in context.
 The keyword All specifies that the action is performed on all the lines

292
Action, Event Framework and Key Definition

Example:
[Key: Cancel Object]
Key : Ctrl + X
Action : Cancel Object
Scope : Current
If Scope is not specified, it is defaulted to ‘Selected Lines’, if there are any selections availa-
ble, else it defaulted to current. This reduces the requirement for the number of ‘Key’ descrip-
tion and shortcut for each action, as most of the actions typically support a selected and current
scope, now this can be achieved by using a single ‘Key’. Note that if scope is specified the
behaviour will be identical.
For the actions Print Report, Mail Report, Export Report and Upload Report while writing the
action statement a report name can be given. This allows user to print a different report other
than using the report available in Context as specified in the Scope. In the absence of the
Report Name parameter the current report is taken. If the scope is not specified the default
scope is ‘Report’. Report Scope makes the Report Level Object available in the Acted Report
i.e. the report name specified with action.
7.5.1 Limitations and Tips for Actions
 A ‘Menu’ Action acts only on a ‘Menu’ Definition, and vice-versa.
 A ‘Report’ Definition can be acted upon by most of the other ‘Actions’ except
‘Menu’ Action.
 If a Menu item doesn't have an Action, default will be ‘Quit’.
 Action can also take arguments; these are separated by colon (:)

Exercise 7.4
Objective
The objective of this program is to understand the Action Association at Button with Scope
Capabilities Used
 Scope attribute at Button Definition
 Mode attribute at Button Definition
 Actions Remove Line, Select All, Unselect All

293
Action, Event Framework and Key Definition

Code
[Report: Exer Button Action with Scope]
Use : Day Book
Delete : Form
Add : Form : Exer Button Action with Scope

[Form: Exer Button Action with Scope]


Use : Day Book
Buttons : Exer BAS RemoveSelected, Exer BAS RemoveUnselected, +
Exer BAS BtnSelectAll, Exer BAS Btn UnSelect All

[Button: Exer BAS RemoveSelected]


Key : Alt + R
Action : Remove Line
Mode : Display
;; Here this attribute Scope means that the Action Remove Line should be carried on for Selected lines
Scope : Selected Lines
Title : "Remove Selected"

[Button: Exer BAS RemoveUnselected]


Key : Ctrl + R
Action : Remove Line
Mode : Display
;; Here scope means that the Action Delete Object should be carried on for Unselected lines
Scope : Unselected Lines
Title : "Remove Unselected"

[Button: Exer BAS Btn Select All]


Key : Alt + S
;; Newly introduced action wherein all the lines (Selected/Unselected) will be selected
Action : Select All
Mode : Display
Title : "Select All"

294
Action, Event Framework and Key Definition

[Button: Exer BAS Btn UnSelect All]


Key : Ctrl + S
;; Newly introduced action wherein all the lines Selected Lines will be unselected
Action : UnSelect All
Mode : Display
Title : "Unselect All"
;; End-of-File

Output

Program Explanation
The above reports are displayed the daybook to demonstrate the scope of actions. The Buttons
called Remove selected, Remove unselected, select all, and unselect all are added to the
form Exer Button Action with Scope. The buttons trigger the Actions to select the lines,
unselect the line and remove the selected or unselected lines.
The first report shows the selected lines from the report by using the button Select All and the
scope of this report is set as selected lines. The second report the scope is set as unselected
lines.

295
Action, Event Framework and Key Definition

The Button Exer BAS RemoveSelected is defined with the action Remove Line and the
scope as Selected Lines, i.e., the action Remove line is performed only for selected Lines.
Refer all the buttons in the code for the action it triggers and the scope for which it is applica-
ble.
7.6 Dynamic Actions
Dynamic Action capability allows the programmer to execute actions based on dynamic eval-
uation of parameters. The Action keyword can as well be evaluated dynamically. Normally
this would be useful for specifying condition based action specification in menu, key / button
etc. In case of functions, as the function inherently supports condition based actions via IF
ELSE etc, this would be useful when one required to write a generic function, which takes a
parameter and later passes that to an action (as its parameter) which does not allow expres-
sions and expects a constant.
This has been achieved with the introduction of the keyword "Action”. The syntax for specify-
ing the same is as given below.
Syntax
Action :<Action Keyword Expression>: <Action Parameter +
Expression>
Where,
Action is the keyword "Action" to be used for Dynamic Actions usage
<Action Keyword Expression> is an expression evaluating to an Action Keyword
<Action Parameter Expression> is an expression evaluating to Action Parameters
We can specify and initiate an Action from the following
 Menu Item
 Key Definition
 In a User Defined Function
At present the capability is valid for
 System Actions like Display, Alter etc
 System Actions inside User Defined Functions

Example:1
Dynamic Actions in Key/Button Definition
[Button: Test Button]
Key : F6
Action : Action : Display : @@MyFor
;; The Button Test Button initiates a dynamic Action which takes the parameter as a formula

296
Action, Event Framework and Key Definition

[System : Formula]
MyFor : if ##SVCurrentCompany CONTAINS "ABC" Then "BalanceSheet" +
else "TrialBalance"

Observe the usage of Action keyword twice in this. The first usage is the
attribute "Action" for key definition. The second is the keyword "Action" intro-
duced specifically for executing Dynamic Actions.

Example:2
Dynamic Actions in User Defined Functions
[Button: Test Button]
Key : F6
Action : Call:TestFunc:"Balance Sheet"

[Function: Test Func]


Parameter : Test Func : String
;;The function Test Func executes a dynamic action which takes Action parameter as the parameter passed to the function
01 : Action : Display : ##TestFunc
Exercise 7.5
Objective
The objective of this program is to understand the usage of Dynamic Actions and Action
Parameters.
Capabilities Used
 Using dynamic actions Display, Create, Print, Export, Mail
 No confirm attribute at Form level

Code
[Report: Exer Dynamic Action]
Form : Exer Dynamic Action
Title : "Dynamic Actions"

[Form: Exer Dynamic Action]


Parts : Form SubTitle, Exer Dynamic Action
Local: Field: Form SubTitle: Info: "Dynamic Actions"

297
Action, Event Framework and Key Definition

Width : 50% Page


No Confirm : Yes
;; On Acceptance of this Form, the user Selected Action will be triggered with the user selected Report
On: Form Accept : Yes : ACTION: #ShortNameField: #NameField

[Part: Exer Dynamic Action]


Lines : Exer Dynamic Action

[Line: Exer Dynamic Action]


Fields : Short Prompt, Short Name Field, Medium Prompt, Name Field
Local : Field: Short Prompt: Info : "Action :"
Local : Field: Medium Prompt: Info : "Report :"
Local : Field: Short Name Field: Table: Exer DA Actions
Local : Field: Short Name Field: Show Table: Always
Local : Field: Name Field: Table: Exer DA Reports Display:+
#ShortNameField != "Create"
Local : Field: Name Field: Table : Exer DA Reports Create:+
#ShortNameField = "Create"
Local : Field: Name Field: Show Table: Always
Local : Field: Name Field: Set Always: Yes
Local : Field: Name Field: Dynamic: ""

[Table: Exer DA Reports Display]


List Name : Balance Sheet, Profit and Loss, Trial Balance, +
Cost Category Summary
List Name : Cash Flow, Funds Flow, Bills Receivable, Bills Payable,+
Day Book
List Name : Sales Register, Purchase Register, Sales Orders, +
Purchase Orders
List Name : Statistics, Bank Group Summary, Receipts and Payments
List Name : Ratio Analysis
Title : #ShortNameField + " Report"

298
Action, Event Framework and Key Definition

[Table: Exer DA Actions]


List Name : Display, Create, Print, Export, Mail
Title : "List of Actions"

[Table: Exer DA Reports Create]


List Name : Ledger, Group, Stock Group, Stock Item
Title : "Create Report/Object"
;; End-of-File

Output

Program Explanation
The above report displays the list of actions to be triggered and the Report name on which it is
performed, based on the selection from the table. When the user accepts the form Exer
Dynamic Action, it triggers the user-selected action. ShortNameField holds the action name,
which has to be performed, and NameField holds the ReportName on which it is to be per-
formed. The values from the corresponding fields are passed as parameters to the action
Action which is used for trigerring the dynamic action.

7.7 Frequently used System and Object Specific Actions


7.7.1 System Actions
System Actions are mainly performed on three principal definition types namely Report, Col-
lection and Menu. Some of the frequently used Global Actions are discussed below:

299
Action, Event Framework and Key Definition

Action — Menu
A menu action acts only on the menu definition and vice versa. The value of a menu action
must be a Menu name. This menu has to be further defined to list the items displaying another
Menu or a Report. A menu definition continues until all the items are used to display Reports
and there are no further menu actions assigned to the final menu items.
Example:1
;; The following code demonstrates the usage of Action Menu along with further Menu Definitions
[#Menu: Gateway of Tally]
Add: Key Item: Sample Final Accounts : F : Menu : +
Sample Final Accounts
[Menu: Sample Final Accounts]
;; Menu Definition to display when the above Item is activated
Add : Key Item : Trial Balance : T : Display : Trial Balance
Add : Key Item : Profit & Loss : P : Display : Profit and Loss
Add : Key Item : Balance Sheet : B : Display : Balance Sheet
In the example mentioned above:
 The default menu Gateway of Tally is altered to add a new item Sample Final
Accounts with Menu action displaying the Sample Final Accounts Sub Menu.
 The Sub Menu Sample Final Accounts is defined to display all the components of
Final Accounts i.e.,
Trial Balance

Profit & Loss

Balance Sheet

 All the Items here use the Display Action. Hence, no further Menu Definition is
required.
Example:2
/* The following code demonstrates the usage of Menu and Display Actions and also the relevance of their association in Menu
and Reports (through Form)*/

[Button: Final Accounts]


;; Button Definition to activate a Menu
Key : F5
Action : Menu: Sample Final Accounts
/* Since the above Button activates a Menu, it can be acted only upon a Menu. It cannot be associated to a Report */

[#Menu: Gateway of Tally]


Buttons : Final Accounts

300
Action, Event Framework and Key Definition

;; attaching a Button to the Menu

[#Form: Group Summary]


Buttons : Final Accounts
;; Above is an incorrect association as Buttons triggering Menu Action cannot be attached to a Form.

[Button: Balance Sheet]


;; Button Definition to Display a Report
Key : F6
Action : Display: Balance Sheet
/* Since the above Button activates a Report, it can be associated both to a Menu as well as a Report */

[#Form: Group Summary]


Button : Balance Sheet;; attaching a Button to the Report
[#Menu: Display Menu]
Button : Balance Sheet
;; attaching a Button to the Menu

In the Example mentioned above:


 A new Button Final Accounts is added to activate a Menu Sample Final Accounts
which is attached to the default Menu Gateway of Tally.
 The Button Final Accounts cannot be attached to a Report since a Menu cannot be
acted upon in a Report. In the above example, the Button Final Accounts is attached
to the Form Group Summary which is incorrect since the Menu cannot be called
from a Report.
 Another Button Balance Sheet is added to display a Report Balance Sheet which is
enabled in all the Reports using the Form Group Summary and also in the Menu Dis-
play Menu.
 The Button Balance Sheet can be attached both to a Report as well as to a Menu
since the Report can be acted upon by a Report as well as a Menu.

Action – Display, Print, Execute


These actions are used to activate the Report in Display, Print or Execute mode. The display
action is used to display the values, print is used to print the values and Execute is used to
perform some operation and to display the result.
[Menu: Display and Display Collection]
Key Item : Sundry Debtors Details : D : Display : SD Address Book

301
Action, Event Framework and Key Definition

Key Item : Sundry Creditors Details : C : Display : SC Address Book

Action – Browse URL


Action Browse URL is used to provide a link to any web browser with a URL formula passed
as a parameter. This action opens the item specified by the parameter. The item can be a file or
folder or URL or Exe. If no parameter is there by default it will launch Tally website.
Syntax
Action: Browse URL: <URL Formula>
<URL Formula> is the parameter for the action Browse URL and it can be any URL address
Example:
Field acting as a hyperlink

[Key : Execute Hyperlink]

Key : Left Click


Action : Browse URL: www.tallysolutions.com

[Field : Hyperlink Company]

Color : Blue
Border : Thin Bottom
Key : Execute Hyperlink
Set as : "Tally Solutions Pvt. Ltd"
Local : Key :Execute Hyperlink: Action: Browse URL: +
http://www.tally.co.in
Action – Display Collection
A Menu Item or a Button can be used to display a popup of Object names in a Collection,
which in turn, can trigger a Report. On choosing an Object from the popup, a report in display
mode is triggered by the action, Display Collection. This action can be used for displaying the
Masters or Reports pertaining to Groups, Ledgers, Stock Items, etc.
Example:
;; The following code demonstrates the usage of Display Collection Action
[#Menu: Gateway of Tally]
Add : Key Item: Ledger : L : Display Collection : Ledger
;; where Ledger is a predefined Collection in DefTDL

302
Action, Event Framework and Key Definition

Though the Action name is Display Collection, Display is meant for the subsequent Report,
which will be displayed on selection of an Object. Here, the Report is in display mode.

Example 7.6
Objective
The objective of this program is to understand the Action 'Display Collection'. In this Code,
list of Groups are displayed in a Trigger Report and on selection, subsequent Report is
displayed with SubGroups, Ledgers along with their Closing Balances.

Capabilities used
 Action Display Collection
 Collection Definition and its attributes in context of usage with Display Collection
 Usage of Trigger attribute

Code
;; This Collection 'Exer DC Group Summary' is used to Display when the Menu Item 'Display Collection' is selected by
user
[Collection: Exer DC Group Summary]
Type : Group
/* Collection Attribute 'Trigger' accepts a Report Name which is used to display the preselection Report with the Table
for Selection*/
Trigger : Exer DC GS Trigger Report
;; Collection Attribute 'Report' accepts a Report Name which is used to display the Report post selection of the Required
Object
Report : Exer DC GS Final Report
/*Variable 'GroupName' retains the selected variable from the Trigger Report and is used to display the Final Report for
the selected Object*/
Variable : GroupName
Filter : Exer DC Non Empty Bal
;; Initial Trigger Report begins here

[Report: Exer DC GS Trigger Report]


Use : Collection Variable
Title : $$Sprintf:@@SelectGdwn:@@GdwnTitle
Local : Line : Collection Variable: Field : Exer DC GS Trigger+
Report

303
Action, Event Framework and Key Definition

Local : Field: MV Title: Info: "Name of Group"


Title : "Display Collection-Select Group"

[Field: Exer DC GS Trigger Report]


Use : Name Field
;; Collection 'Exer DC Group Summary' is used to display list of Objects for user selection
Table : Exer DC Group Summary
Show Table : Always
Key : Create Group
;; Selected Object is stored in this variable 'GroupName' which is accessed across Reports
Modifies : GroupName
;; Final Report begins here

[Report: Exer DC GS Final Report]


Form : Exer DC GS Final Report
Title : "Display Collection-Group Summary"

[Form: Exer DC GS Final Report]


Parts : Form SubTitle, Exer DC GS Final Report
Local : Field: Form SubTitle: Info: "Understanding Action+
Display Collection - Sub Groups and Ledgers within +
Group " + ##GroupName

[Part: Exer DC GS Final Report]


Lines : Exer DC GS Final Report Title, Exer DC GS Final Report
BottomLines : Exer DC GS Final Report Total
Repeat : Exer DC GS Final Report: Exer DC GS GrpandLed
Scroll : Vertical
CommonBorder: Yes
Total : Amount Field

304
Action, Event Framework and Key Definition

[Line: Exer DC GS Final Report Title]


Use : Exer DC GS Final Report
Local: Field: Default: Type: String
Local: Field: Default: Align: Center
Local: Field: Default: Style: Normal Bold
Local: Field: Default: Lines: 0

Local: Field: Name Field: Set As: "Name"


Local: Field: Amount Field: Set As: "Closing Balance"
Border : Thin Top Bottom

[Line: Exer DC GS Final Report]


Fields : Name Field
Right Fields : Amount Field

Local: Field: Name Field: Set As: $Name


Local: Field: Name Field: FullWidth: Yes

Local: Field: Amount Field: Border: Thin Left


Local: Field: Amount Field: Set As: $ClosingBalance

Option : Exer DC GS Final ReportLed: $$IsLedger

[!Line: Exer DC GS Final ReportLed]


Local : Field: Default: Style: Normal

[Line: Exer DC GS Final Report Total]


Use : Exer DC GS Final Report
Local: Field: Default: Align: Center
Local: Field: Default: Style: Normal Bold

305
Action, Event Framework and Key Definition

Local: Field: Name Field: Set As: "Total"


Local: Field: Amount Field: Set As: $$Total:AmountField
Border : Thin Top Bottom

[Collection: Exer DC GS GrpandLed]


Collection: Exer DC GS Grps, Exer DC GS Leds

[Collection: Exer DC GS Grps]


Type : Group
;; Value of Variable 'GroupName' is passed from the Trigger Report where the required Object is selected by the user
Child Of : ##GroupName
Filter : Exer DC Non Empty Bal

[Collection: Exer DC GS Leds]


Type : Ledger
Child Of : ##GroupName
Filter : Exer DC Non Empty Bal

[System: Formula]
Exer DC Non Empty Bal: NOT $$IsEmpty:$ClosingBalance
;; End-of-File

306
Action, Event Framework and Key Definition

Output

307
Action, Event Framework and Key Definition

Program Explanation
The Action Display Collection is triggered from the menu item. Within the collection defini-
tion Exer DC Group Summary the Trigger attribute specifies the report name Exer DC GS
Trigger Report which pops up a table of Groups for the user selection. Based on the Group
object selected, the corresponding report Exer DC GS Final Report specified with the Report
attribute is displayed with the ledgers and subgroups belonging to the group object selected in
the trigger report. The collection Exer DC GS Grps and Exer DC GS Leds filters the groups
and the ledgers based on the group selected i.e it applies the Child Of attribute to filter the
ledgers and groups.
Action – Print Collection
Menu Action Print Collection triggers a list and it displays the final Report in Print mode
based on user selection. This action is used to print the Collection of objects. Eg; Stock
Vouchers, Ledger Vouchers, Ledger Out Standings etc.
Syntax
[Menu: Menu Name]
Add: Key Item: [Position] : <Display Item> :<Unique Key>+
: <Action Keyword>:<Action Parameter>

308
Action, Event Framework and Key Definition

Where,
Action Keyword can be Print Collection which triggers a list and displays the final report
based on user selection
Example:
[#Menu: Printing Menu]
Add: Key Item: My Ledgers : L : Print Collection: Ledger Vouchers
In the above example, we have added the Item My Ledgers, which has an action Print Collec-
tion associated to it. It displays a collection bearing the List of ledgers which on user selection
enters the final report in Print Mode. On accepting it directly goes to the printer.

7.8 Object Specific Actions


Object Specific Actions are specific to a particular User Interface Object on which it is applied

7.8.1 Menu Actions – Menu Up, Menu Down, Menu Reject


Menu Actions - Menu Up, Menu Down, Menu Reject, etc. are acted upon on the Menu. These
keys are associated to all the Menus (Default TDL codes as well as User Defined TDL codes)
through the declaration [System: Menu Keys]
Example:
[#Menu : Gateway of Tally]
Add: Key Item: Action Demo : D : Menu : Action Demo
[Menu: Action Demo]
Add : KeyItem : Menu Action Demo : M : Menu : Menu Action Demo

[Menu : Menu Action Demo]


Add : KeyItem : Menu Action 1
Add : KeyItem : Menu Action 2
Add : KeyItem : Menu Action 3
Add : KeyItem : Menu Action 4

[Key: User Menu Up]


Key : Alt + U
Action : Menu Up

309
Action, Event Framework and Key Definition

[Key: User Menu Down]


Key : Alt + D
Action : Menu Down

[Key: User Menu Reject]


Key : Alt + Esc
Action : Menu Reject

[System: Menu Keys]


Key : User Menu Down, User Menu Up, User Menu Reject
In the above program Menu Action 1 – 4 are the menu items. User Menu Up, User Menu
Down, User Menu Reject are the three keys which is having actions called Menu Up, Menu
Down and Menu Reject. For each action different keys are defined.
The declaration [System: Menu Keys] declares a list of Keys that are commonly required for
any Menu. Since all the common menu operations like Scroll Up, Scroll Down, Drill down,
etc. are declared here; a new Menu added, does not require these keys to be associated since
they are inherited from the above declaration.

TDL Control of Keys and Buttons


In the menu, you will observe that when you use the downward arrow key,
the cursor moves to the next item, which is not explicitly defined in the
menu but is TDL controlled. Here the system uses system specific defini-
tions, which have been defined for all Menus, as given below.
[System: Menu Keys]
Key : MenuUp, MenuTop

Form Actions – Form Accept, Form Reject, Form End


Form Actions: Form Accept, Form Reject, Form End, etc. are performed on the Form. These
keys are associated to all the Forms through the declaration [System: Form Keys]
 Action Form Accept saves the current Form
 Action Form Reject rejects the current Form i.e., the current form is quit without
saving
 Action Form End closes the current Form

310
Action, Event Framework and Key Definition

Example:
[Key: Form Accept]
Key : Ctrl + A
Action : Form Accept
Mode : Edit

[Key: Form Display Reject]


Key : Esc
Action : Form Reject
Mode : Display

[Key: Form End]


Key : Ctrl + End
Action : Form End

[System: Form Keys]


Key : Form Accept, Form Display Reject, Form End

The declaration [System: Form Keys] declares a list of Keys that are commonly required for
any Report. Since all the common Form operations like Save Form, Reject Form, Form End,
etc. are declared here; a new Form added does not require these keys to be associated since
they are inherited from the above declaration.

Part Actions – Part Home, Part End, Part Pg Up


Part Actions- Part Home, Part End, Part Pg Up, etc. are acted upon Part. These keys are asso-
ciated with all the Parts (Default TDL codes as well as User Defined TDL codes) through the
declaration [System: Form Keys].
 Action Part Home positions the cursor to the beginning of the current Part
 Action Part End positions the cursor to the end of the current Part
 Action Part PgUp is used to quickly scroll the page to view the previous page
Example:
[Key: Part Display Home]
Key : Home
Action : Part Home

311
Action, Event Framework and Key Definition

Mode : Display

[Key: Part Display End]


Key : End
Action : Part End
Mode : Display

[Key: Part Display PgUp]


Key : PgUp
Action : Part PgUp
Mode : Display

[System: Form Keys]


Key : Part Display Home, Part Display End, Part Display PgUp

The declaration [System: Form Keys] declares a list of Keys that are commonly required for
any Part. Since all the common Part operations like Part Home, Part End, Part PgUp, etc. are
declared here; a new Part added does not require these keys to be associated since they are
inherited from the above declaration.

Line Actions – Explode, Display Object, Alter Object


Line Actions: Explode, Display Object, Alter Object, etc. are acted upon Line.
 Action Explode explodes a line further to display all the explode details specified in
the Line Attribute Explode.
 Action Display Object is used to display the Object in context of the current line.
 Action Alter Object is used to alter the Object in context of the current line.
Example:
[Key : Line Explode]
Key : Shift + Enter
Action : Explode

[Key : Line Object Display]


Key : Enter

312
Action, Event Framework and Key Definition

Action : Display Object


Mode : Display

[Key: Line Object Alter]


Key : Ctrl + Enter
Action : Alter Object
Mode : Display

[System: Form Keys]


Key : Line Explode
Key : Line Object Display, Line Object Alter

The declaration [System: Form Keys] declares a list of Keys that are commonly required for
any Line. Since all the common Line operations like Explode, Display Object, Alter Object,
etc. are declared here; a new Line added does not require these keys to be associated since they
are inherited from the above declaration.

Field Actions – Field Copy, Field Paste, Field Erase, Calculator


Field Actions: Field Copy, Field Paste, Field Erase, Calculator, etc. are acted on Fields.
 The Action Field Copy, copies the current field (Field where the cursor is positioned)
con¬tents in the OS clipboard which will be available later.
 The Action Field Paste, pastes the clipboard contents to the current Field.
 The Action Field Erase, is used to erase the contents of the current Field at a stretch
without hitting the Backspace or Delete Key.
 The Action Calculator is used in case of Fields that requires some computation, the
result of which should be returned to the Field. Fields which take Amounts or Num-
bers as their value require this action.

Example:
[Key : Field Copy]
Key : Ctrl + Alt + C
Action : Field Copy

[Key : Field Paste]

313
Action, Event Framework and Key Definition

Key : Ctrl + Alt + V


Action : Field Paste

[Key: Field Erase]


Key : Esc
Action : Field Erase
Mode : Edit

[Key: Calculator]
Key : Alt + C
Action : Calculator
Mode : Edit

[Field : NumDecimals Field]


Key : Calculator

[System: Form Keys]


Key : Field Erase
Key : Field Copy, Field Paste

The declaration [System: Form Keys] declares a list of Keys that are commonly required for
any Field. Since all the common Field operations like Field Copy, Field Paste, Field Erase,
etc. are declared here; a new Field added does not require these keys to be associated since
they are inherited from the above declaration. The Action Calculator is not required for all the
Fields hence it has not been declared in Form Keys usage List. The Action Calculator has
been associated to Fields where it is required. In the above example, NumDecimals Field is a
numeric field which may require calculations. Therefore, the Calculator Key associating the
Action Calculator is attached to the Field.

The complete listing of the various Predefined Actions and the related help is
available within the Action Browser provided with Tally.Developer 9.

314
Action, Event Framework and Key Definition

7.9 Key Definition


We have already covered in previous sections that key is the fundamental definition which is
used to trigger an action. We will now discuss the key definition and its various attributes in
detail.
An Action is associated with a key/button definition in order to be invoked. The particular key
combination is also specified within the definition. Button/Key are alias of each other. On
clicking the Button or the associated key combination the relevant Action/sequence of Action
takes place.

The figure above displays the buttons and keys.


A button always has to refer to a key, but a key definition can exist on its own.There is no
button existing for this key, yet the user can deliver action by pressing the respective key com-
bination.
Syntax
[Key : <Key Name>]
Option : <Key Name>
Key : < Key Name> / <Key Combination>
Action : <expression list>
Action List : < Key / button name/s >
Mode : [Display / Edit / Both]
Inactive : < Logical Condition >

315
Action, Event Framework and Key Definition

Print : [Yes / No]


Title : <Title String>

7.9.1 Attributes of the Definition Button / Key


The attributes of ‘Key’ definition are listed as shown in the following Table.
Attribute Parameters Type
Option Key Name Multiple
Keys Key Value Single
Action Action keywords Single
Action List List of Keys Multiple Serial
Title String Formula Single
Inactive Logical Single
Mode  Edit Single
 Display
 Both
Print Yes/No Single
Type Button Name / Key Single
Name
The attribute Option
Syntax
Option: <Key Name>
The attribute option takes value as another key / button name. While defining this optional
key the symbol ‘!’ is used before the definition Key. In all other means there are no restric-
tions on the key defined with the symbol ‘!’. i.e. it can further have option attribute defined
under it. A typical example of usage of this attribute is Alt+F1 key used to see the detailed or
condensed Balance Sheet, Trial Balance, Profit & Loss A/c etc.
Example:
(i) Path: “voucher\vchkeys.500”
[Button: SetRejOutType]
Key : Alt+F6
Option : Normal RejOut Button: @@NumRejOut = 1
Option : ChgVchType: @@NumRejOut >1

316
Action, Event Framework and Key Definition

Option : LinuxAlt2ShiftF6: NOT $$IsWindows

(ii) Path: “voucher\vchkeys.500”


[Button: SetAttdType]
Key : Ctrl+F5
Option: Normal Attd Button: @@NumAttd = 1
Option: ChgVchType: @@NumAttd > 1

The attribute Key


Syntax
Key : <Key Name> / <Key Combination>
The attribute key determines which key combination the user wants to implement. The key
can take following values:
 All function keys, Navigational keys. INS, DEL, Backspace, Enter, TAB, ‘+’, ‘-‘
 Combination of the above keys with ALT, SHIFT, CTRL
 Combination of ALT, SHIFT, CTRL, with Alphabets, Numerals, and/or Function
keys, navigational keys.

Same key combination can be repeated across reports functioning indifferently of each other.
An example in default TDL can be that of ALT+C. It triggers actions such as Create Ledger,
Create Group, Create Cost Centre, Create Stock Item, Calculator, advanced calculator etc.
Example:
(i) Path: “master\mbasic.500”
[Button: Master Group]
Key : Ctrl+G
Action : Replace : Group
Title : $$LocaleString :”Groups”

(ii) Path: “master\mbasic.500”


[Button: Master Ledger]
Key : Ctrl+L
Action : Replace: Ledger
Title : $$LOcaleString:”Ledgers”

317
Action, Event Framework and Key Definition

Examples for Key Creation


(i) Path: “master\mbasic.500”
[Key: Create Group]
Key : Alt+C
Action : Create: Group
(ii) Path: “master\mbasic.500”
[Key: Create Ledger]
Key : Alt+C
Action : Create: Ledger

If you create the Buttons, it will be visible in the tally screen. But, the key is not.

The attribute Action


Syntax
Action : <expression list>
The most important attribute of the definition Key, determines the Action to be triggered when
the key is pressed. The expression list for the attribute action takes two forms

Action : <Action Keyword> : <Action Parameter>


Example:
Action: Display: My Report
The other type of syntax is
Action : <Predefined Key Name>
Example:
Action: Next Report

Where Next Report is key already defined in TDL. Following are the actions which can be
specified with the attribute Action.
Key Actions:
Set : Variable Name or Field Name: Formula
Multi Field Set : List of Field Names: Formula
Auto Set : Field Name : Formula

318
Action, Event Framework and Key Definition

Create/Execute : Report Name


Insert : Report Name
Append : Report Name
Duplicate : Report Name
Alter : Report Name
Display : Report Name
Replace : Report Name
Menu : Menu Name
Auto Columns : Report Name
Alter Collection: Collection Name
Modify Variables: Report Name
Modify Variables Only: Report Name
Modify Original : Report Name
Modify System : Report Name
Select Display : Report Name
Related Display : Report Name
Exchange : Variable Name: Variable Name

Example:
(i) Path: “voucher\vchkeys.500”
[!Button : Normal RejOut Button]
Action : Set : SV Voucher Type: $$VchTypeRejOut
(ii) Path: “voucher\vchkeys.500”
[Button: Master Group]
Key : Ctrl+G
Action : Replace: Group
Title : $$LocaleString:”Groups
The attribute Action List
Syntax
Action List : <Key / button name/s>

319
Action, Event Framework and Key Definition

The attribute Action List allows the TDL programmer to activate more than one action at a
time. The parameters given are key / button names. These parameters (Key / button names)
have to have the same key combinations as the key where in the attribute Action List is
defined.
A typical example of the application of this attribute is the Quick Format / Neat Format button
which automatically selects / de-selects the columns / fields depending upon whether the form
is printed in draft mode or neat mode.
Example:
(i) Path: “voucher\vchkeys.500”
[Button: VCHInventory]
Key : F1
ActionList: VCH Set Inventory, VCHPayroll
(ii) Path: “voucher\vchkeys.500”
[Button: SalesOrderButton]
Key : Alt+F5
Title : $$LocaleString:”Sales Order”
ActionList: VCHInventory, SetChgSalesOrder, SetSalesOrderType
The attribute Mode
Syntax
Mode: [Display / Edit / Both]
The attribute Mode specifies whether the action associated to the key has to be applied in
Display mode, Edit mode or both the modes. If this attribute is not specified in the Key defini-
tion, then the default mode is Both.
Example:
(i) Path: “keys.500”
[Key: Field Insert Mode]
Key : Insert
Action : Field Insert Mode
Mode : Edit
(ii) Path: “keys.500”
[Key: Field Display Next]
Key : Right
Action : Field Next
Mode : Display

320
Action, Event Framework and Key Definition

The attribute Inactive


Syntax
Inactive : <Logical Condition>
The attibute Inactive takes a condition as the parameter. If the given condition is satisfied,
then the key takes no effect, ie as the name suggests, the key becomes inactive.
Example:
(i) Path : “buttons.500”
[Button: Change Company]
Key : F3
Action : Modify Variable : Change Current Company
Title : $$LocaleString:”Company”
Inactive : $$SelectedCmps < 2
(ii) path: “master\mbasic.500”
[Button: Master StockCat]
Key : Ctrl+C
Action : Replace : Stock Category
Title : $$LocaleString:”Category”
Inactive :NOT IsStockCategoryOn:Company:##SVCurrentcompany

The key can be made identifiable by using the rules given below.
The key should be a function key: F1, F2 etc.
The key could be defined based on the following combinations
Function keys from F1 to F12
Combination of Ctrl/Alt + Function keys
Combination of Ctrl/Alt + Alphabet etc.
If the key is defined, using the combination of alphabets then that alphabet
should be a part of the key definition name.
 The Button and Key definition do have a co-relation. Key can exist by
itself whereas Button always needs a Key to be defined.

321
Action, Event Framework and Key Definition

7.10 Event Frame Work


We have already introduced you to events in the previous topics. We will cover the Event
handling in TDL in detail and also the various System and Object specific events available.
In any language event handling is one of the powerful features as it allows the developer to
perform some operation based on some implicit action. In order to detect the events and to
perform some action based on the event a proper Event Frame work is required. Let us start
with a brief overview of Event Framework and type of events.

7.10.1 Understanding TDL Events


When the user does something an event takes place. Events are action which are detected by a
program and can change the state of system or the executin flow. Events can occur based on
user actions or can be system generated. In TDL, the Key Framework is mainly used to handle
user actions like keyboard and mouse events. This can be considered to be a part of Event
Framework. As we know that TDL is a definition language which does not have any explicit
control on the flow of execution, the programmer has no control over what will happen when a
particular event occurs. We have certain attributes like SET/PRINTSET which are used to
initiate some action on occurrence of event/change of state (like report construction etc). In
this scenario there is a need of generic Event Framework, which allows the programmer to
trap the events and initiate actions/set of actions at a state when the event has occurred.
The event framework allows the specification of Event Handler where it is possible to specify
Event Keyword, a condition to control event handling and the Action to be performed. The
process to detect an event and then execute the specified action is called as event handling.

7.10.2 Different Types of Events In TDL


When user operates the application different types of events are generated. The events are
classified as System Events or Object Specific Events based on their origin.
System events are events for which no object context is available when they occur. Eg Tally
application launch.
The events that are performed only if the specific object context is available are referred as
Object Specific events.
Eg. Form Accept event is Form specific event.

System Events
In TDL a new type “Events” is introduced in System definition. All the system events are
defined under this definition. As of now TDL event framework supports following four
system events viz. System Start, System End, Load Company, Close Company.

322
Action, Event Framework and Key Definition

Syntax
[System: Events]
Label : EventKeyword : ConditionExpr : ActionKeyword :+
Action Parameters
Where,
<Label> is name assigned to the event handler. This has to be unique for each event handler.
<EventKeyword> can be any one of System Start, System End, Load Company, Close
Company.
<ConditionExpr> should return a logical value
<ActionKeyword> any one of the actions
<Action Parameters> parameters of the actions specified

The events System Start, System End are executed when the user launches or quits Tally appli-
cation respectively.
The events Load Company, Close Company are executed when the user loads or closes a
company respectively.

Example:
[System: Events]
AppStart1: System Start : TRUE : CALL : MyAppStart
The function ‘MyAppstart’ is called as soon as Tally application is launched. The following
are mainly used system events in TDL.
 System Start
 System End
 Load Company
 Close Company
7.10.3 Object Specific Events
Objects specific events can be specified for the associated object only. Eg. Before Print event
is specific to report object.
The attribute ON is used to specify the object specific events as follows:
Syntax
ON : EventKeyword : ConditionExpr : ActionKeyword : +
Action Parameters

323
Action, Event Framework and Key Definition

Where,
<EventKeyword> can be any one of Focus, Form Accept, Before Print and After Print,
on:Import etc.
<ConditionExpr> should return a logical value
<ActionKeyword> any one of the actions
<Action Parameters> parameters of the actions specified.
ON is a list type attribute, so list of actions can be executed sequentially when the specific
event occurs.

7.10.4 Event – Form Accept


The event Form Accept is specific to Form object hence can be specified only within Form
definition. A list of actions can be executed when the form is accepted which can also be based
on some condition. After executing the action Form Accept, the current object context is
retained. So, all the actions that are executed further will have the same object context.
The event Form Accept when specified by the user overrides the default action Form Accept.
So when Form Accept event is triggered then the Form will not be accepted until the user
explicitly calls the action Form Accept.
Example:
[Form : TestForm]
On : FormAccept : Yes :HttpPost : @@SCURL : ASCII : SCPostNewIssue+
:SCNewIssueResp
The action Http Post is executed when the event Form Accept is encountered. But the form
will not be accepted until the user explicitly calls the action Form Accept on event Form
Accept as follows:
On : FormAccept : Yes : Form Accept
Now after executing the action Http Post, Tally will execute the action Form Accept as well.
7.10.5 Event – Focus
The event Focus can be specified within definitions Part, Line and Field. When Part, Line or
Field receives focus, a list of actions get executed which can also be conditionally controlled.
Example:
[Part : TestPart2]
On : FOCUS : Yes : CALL : SCSetVariables : $$Line

324
Action, Event Framework and Key Definition

7.10.6 Event – Before Print


The event Before Print is specific to Report object so it can be specified only within Report
definition. The event Before Print is triggered when the user executes Print action. The action
associated with the event is executed first and then the report is printed.
A list of actions can be executed before printing the report based on some condition.
Example:
[Report : Test Report]
On : BEFORE PRINT : Yes :CALL: BeforeRepPrint
The function ‘BeforeRepPrint’ is executed first and then the report ‘Test Report’ is printed.

7.10.7 Event – After Print


The event After Print can be specified for Report, Form, Part and Line definition. The event
After Print first prints the current interface object and then executes the specified actions for
this event.
A list of actions can be executed after printing the report based on some condition. Print is an
alias for After Print.
Example:
[Line: LV AccTitle]
On : After Print: Yes: CALL : SetIndexLV:#LedgerName
The function ‘SetIndexLV’ is called after printing the line ‘LV AccTitle’. So if there are 10
lines to be printed, the function will be called ten times.

7.10.8 Event – Start Import


The event Start Import can be specified at Import File definition. If the logical condition
specified returns TRUE, event Start Import executes the actions before beginning the import
process. At this stage, the data objects will not be available since it is prior to gathering the
data from the file. This event can be used to communicate any messages to the user like
starting the import process, etc.
Example:
[#Import File: Vouchers]
On : Start Import : Yes : CALL: Start Import
Where “Start Import” is a user defined Action created using Function definition

325
Action, Event Framework and Key Definition

7.10.9 Event – Import Object


The event Import Object can be specified at Import File definition. If the logical condition
specified returns TRUE, Event Import Object executes the actions post gathering the Objects
from the File before importing the same in the current company. At this stage, the data objects
are available since this event is triggered post gathering the data from the file. This event is
actually useful to manipulate & transform the data from one form to another, i.e., from Receipt
Note to Delivery Note, etc.
If the Event Import Object is used, it overrides the default Import Object behavior as a result
of which we need to explicitly specify to being importing the objects. Post performing the
necessary actions prior to importing the objects, Action Import Object must be specified to
instruct the system to continue the import process.
Example:
[#Import File: Vouchers]
On : Import Object : Yes : Call : Change Values
7.10.10 Event – End Import
The event End Import can be specified at Import File definition. If the logical condition
specified returns TRUE, Event End Import executes the actions after importing the objects. At
this stage, the data objects will not be available since it is post importing the objects within the
current company. This event can be used to communicate any messages to the user like ending
the import process, Import Successful, etc.
Example:
[#Import File: Vouchers]
On : End Import : Yes : Call : End Import

With the introduction of Events, Start Import, Import Object and End Import, the programmers
have got complete control to manipulate the data prior to importing the same into the
company. This can be useful in scenarios like data transfers between Inter Branch where
Delivery Note in a branch gets transformed into Receipt Note in the second branch; Sales
transaction in a Branch gets transformed into Purchase transaction in the second branch and so
on. Also, an action Import Object is introduced to begin the Import.
The following example gives the complete idea about the three events which we discussed
now. Here in this example, before importing the data, Narration Method is being altered and
first Ledger Name is being altered to the Branch Ledger. Before starting and after ending the
import process, appropriate messages are being displayed to the user.
Example:
[#Import File: Vouchers]
On : Start Import : Yes : Call : Start Import
On : Import Object : Yes : Call : Change Values

326
Action, Event Framework and Key Definition

On : Import Object : Yes : Import Object


On : End Import : Yes : Call : End Import
[Function: Start Import]
00 : MSGBOX: “Status”: "Starting Import Process"
[Function: Change Values]
00 : SET VALUE : Narration : $Narration + " - Updated by +
Import Object Event"
10: SET TARGET: LedgerEntries[1]
20: SET VALUE: LedgerName: "Branch Ledger"
[Function: End Import]
00 : MSGBOX: “Status”: " Imported data successfully" +
Successful, etc.
Example for Event on: Focus
Let us understand more about the event On: Focus

Exercise 7.7
Objective
The objective of this program is to understand the usage of the Event 'On Focus'

Capabilities Used
 On : Focus at Part, Line & Field
 Function definition with Parameter
 The use of $$Line

Code
[Report: Exer Event On Focus]
Form : Exer Event On Focus
Title : "Event On Focus"

[Form: Exer Event On Focus]


Parts : Form SubTitle, Exer Event On Focus
Local: Field: Form SubTitle: Info: "Understanding Event On Focus"

327
Action, Event Framework and Key Definition

Height : 50% Page


Width : 50% Page

[Part: Exer Event On Focus]


Lines : Exer Info Line, Exer Event On Focus
Repeat : Exer Event On Focus
Break On: $$IsEmpty:#ShortNameField
Scroll : Vertical

[Line: Exer Info Line]


Fields : Info Field
Local : Field: Info Field : Info : "(To quit, press Escape on+
the First Field of any line and accept the field)"
Local : Field: Info Field : Align : Center
Local : Field: Info Field : Width : 50% Page
Local : Field: Info Field : Style : Normal Italic

[Line: Exer Event On Focus]


Fields : Short Name Field
RightFields : Name Field
Local : Field : Default : Width : 25% Page
Local : Field : Default : Align : Center
;; Event 'On Focus’ is triggered when the Field get Focus.
Local : Field: Short Name Field: On: Focus : Yes: SET FIELD:+
"This is Line " + $$String:$$Line + " - Field 1"
Local : Field: Name Field : On : Focus : Yes: SET FIELD: +
"This is Line " + $$String:$$Line + " - Field 2"
Local : Field: Name Field : Inactive: $$IsEmpty:#ShortNameField
/* Event 'On Focus' is triggered when this Line gets focus. Since this is a Repeated Line, this event gets triggered on
every Line and Function 'Exer On Focus Line' is called on each line*/
On: Focus: $$Line > 1 : CALL: Exer On Focus Line: $$Line

328
Action, Event Framework and Key Definition

[Function: Exer On Focus Line]


Parameter : pLine : Number

00 : MSGBOX: "Focus": "Your focus is now shifting to Line " +


($$String:##pLine)
;; End-of-File

Output

Program Explanation
The above report is used to display values in different fields by using on focus action.
Whenever the field get focus then the event get triggered and displays the corresponding
string. Here $$Line is used to get the line number.
Whenever the Line number is greater than 1 then the function Exer On Focus Line called and
it displays one message box with the information on next focus.

329
Chapter 8: Object Manipulation and
Storage in TDL

We have covered the concept of Objects, Methods and Collections in detail in the previous
chapters. There we had concentrated mainly on understanding the object structure, construction
of collections and retrieval of data from the Objects already stored as a part of the Tally
Database.
In this chapter our focus will be on the creation and manipulation of Objects and storing the
same in the Tally Database.
8.1 Object Manipulation & Storage An Introduction
As we already discussed, always information is stored in an object. Internal Objects are objects
provided by the platform. These data objects which are stored as a part of Tally Database can
be manipulated by Tally user i.e., Data can be added, deleted or updated from within Tally.
There are several Internal Objects like Company, Group, Ledger, Stock Group, Stock item,
Unit of measure, Voucher Type, Cost Category, Cost Centre, Budget and so on.
In order to manipulate or retrieve information into the Data Object through the User Interface,
the Data Object needs to be associated with the Interface Object. We have covered the various
association methodologies at the Report, Part, Line and Field level in the chapter on “Objects,
Collections & Internal Object Structure”. Our discussion there was focused on data retrieval
only. Predefined internal methods accessed using ‘$’ is used for data retrieval.
When we talk about manipulation of data, it means that either we need to store an altogether
new data or update the existing data which is stored as a part of the Internal Object. It is very
important to understand the existing structure of the specific Internal Object which is to be
manipulated. Whether it is creation of a new object or updation of an existing object the object
structure has be strictly adhered to. An Object in Tally follows the hierarchical data structure
i.e., an object can consist of methods and sub collections where each sub collection can have
methods and sub collections within it, and this structure can continue up to infinity. When an
Object needs to be manipulated with a particular data/information it needs to be reflected
against the predefined storage name associated with it. The storage name is same as the method
name available with the Object.

331
Chapter 8 - Object Manipulation & Storage in TDL

Detailed hierarchy and schema reference of the various Internal Objects can be
referred to from the Schema Browser Tab available with Tally.Developer 9

8.1.1 Object Manipulation using the Tally Interface(Report & Menu)


Field Attribute – Storage
The Interface Object which is the placeholder for the data either meant to be stored or
retrieved is the definition “Field”. In order to store the data corresponding to the field into an
Object storage name, the attribute used is “Storage”. The field needs to be necessarily associ-
ated with the Data Object being manipulated.
Syntax
At Field Definition:
Storage: <Method Name>: [Collection Name: Direction: [Condi-
tion]]
Where
<Method Name> is the method/storage name being manipulated
<Collection Name > is the name of the Collection whose Object is being manipulated
<Direction> is either First/Last, or the relative Index (+1/-1) of the Object
<Collection Name>: Direction is the complete path of the Object whose method is being
modified ,
<Condition> is the filter condition specifying the Objects being referred.
Example:1
Storage: Name
In the above example the name refers to the method name. The value entered in the field will
be stored in the method “Name” of the object associated with the line of which the field is a
part.
Example:2
Storage : Name : CollName : First

332
Chapter 8 - Object Manipulation & Storage in TDL

The value entered in the field will be stored in the method “Name” of the first object of the
Collection “CollName”.The field is in context of the Object where the collection specified is
available.

Detailed examples will be taken up along with the subsequent topic on


“Create” and “Alter” Action

8.1.2 Data Object Association – Report level


When a particular Data Object is being created/altered using a Report, it is mandatory to
associate the same at Report Level i. e the Report must exist in context of the data object being
manipulated. To put in a simpler way, if an Object needs to be created/altered within a Report
the following needs to be done
 The specified Object needs be associated to the Report using Report Attribute
“Object” as per below
Object: <ObjectType> [: <ObjectIdentifierFormula>]

 Values entered by the user in the Fields within the Report must be stored in relevant
Meth¬ods using Field Attribute- Storage
A Report usually will be associated with a data object, which it inherits from the previous
Report. In case it is the parent Report and no explicit association exists it will be associated
with anonymous object. The Report needs to be opened in the Create or Alter mode as
required.
There are specific Actions to launch a Report in Editable mode. These are the actions Create
and Alter. Create Action is used when a new object needs to be created and stored whereas an
Alter Action is used when some updations are to be performed on an existing Object.
There are specific Actions like “Create Collection” and “Alter Collection” which are used to
Create/Alter specific Objects of the Collection.
Now we will look into detail about how to Create /Alter Objects using the Actions as
mentioned above

8.1.3 Actions for Object Manipulation(Creation and Alteration)


Action – Create
The create action acts only upon the Report definition. This action launches the Report in
Create mode. The Report is invoked in the editable mode where the user can enter values
within the fields. These values are either retained within the Tally Database as a part of
Internal Object or are saved as System Variables and retained as a part of the Configuration
file. This action is used when a New Object is to be created and persisted in the Tally database.

333
Chapter 8 - Object Manipulation & Storage in TDL

All the persistent variable values can be stored in a Configuration File Tal-
lysav.tsf to be retained across sessions. We will be discussing more about
variable in the subsequent chapters.

Exercise 8.1(a)
Objective
The objective of this program is to understand how to create an Internal Object using Action
Create and the attribute Storage.
Capabilities Used
 Usage of the action Create
 Object Association at the report level
 The field attribute- Storage
 The attribute Table at Field level
Code
[Report: Exer Action Create]
Form : Exer Action Create
;; Object Association done at Report Level
Object : Ledger
Title : "Action Create"

[Form: Exer Action Create]


Parts: Form SubTitle, Exer Action Create
Local: Field: Form SubTitle: Info: "Creating an Object using+
Action Create"
Width: 50% Page

[Part: Exer Action Create]


Lines : Exer AC LedgerName, Exer AC LedgerGroup
Horizontal Align: Center

[Line: Exer AC LedgerName]


Fields : Short Prompt, Name Field

334
Chapter 8 - Object Manipulation & Storage in TDL

Local : Field: Short Prompt: Info: "Name :"


/*Storing the value entered by user in an Internal Method Name available within the Object associated at the Report
Level i.e., Ledger*/
Local : Field: Name Field: Storage: Name

[Line: Exer AC LedgerGroup]


Fields : Short Prompt, Name Field
Local : Field: Short Prompt: Info : "Under :"
Local : Field: Name Field : Storage: Parent
Local : Field: Name Field : Table : Group
Local : Field: Name Field : Show Table: Always
SpaceTop: 0.25
;; End of File

Output

Program Explanation
Report Exer Action Create is associated with the Object Ledger which indicates that the
Report is meant for creating an instance of the Object Ledger.
The Name and Group information entered in the fields are stored in the Internal Methods
Name and Parent. This is done by using the attribute storage at the field level.
The field which accepts the value for the method parent displays the table of groups for user
selection.

Action – Create Collection


The Action Create Collection is used to create an Object of Collection thus specified. The Col-
lection definition in turn specifies the Report to be launched for creating the Object ie., the
Report specified with the Report Attribute of the Collection is launched in create mode.

335
Chapter 8 - Object Manipulation & Storage in TDL

Report invoked using the Action Create is terminated as soon as it is saves and return to the
menu. When the action Create Collection is used the Report is invoked repeatedly allowing
the creation of multiple objects till the user quits from the Report.
This action is generally used for creation of Masters such as Groups, Ledgers, Stock Items,
Voucher Types, etc.

Exercise 8.1(b)
Objective
The objective of this program is to understand how to create an Internal Object using Action
Create Collection.

Capabilities Used
 Usage of the action Create Collection
 Collection Attribute Type and Report
 The attribute modifier Use at Report level
Code
[Menu: Exer Object Manipulation and Storage]
Key Item : "Action Create Collection": O : Create Collection:+
Exer Action Create Collection
/*This Collection triggers Report 'Exer Action Create Collection' which is used to Create the Objects. It creates collection
of objects, i.e., On creation of one Ledger, it will continue in the same screen for second*/

[Collection: Exer Action Create Collection]


Type : Ledger
Report : Exer Action Create Collection

[Report: Exer Action Create Collection]


Use : Exer Action Create
Title: "Action Create Collection"
Local: Form: Exer Action Create: Local: Field: Form SubTitle: Info
;; End-of-File

336
Chapter 8 - Object Manipulation & Storage in TDL

Output

Program Explanation
The menu item Exer Object Manipulation and Storage triggers the Action Create Collection
which takes the Collection “Exer Action Create Collection” as the parameter.
The collection “Exer Action Create Collection” is a Collection of type ledger. The Report
attribute of the collection specifies the name of the Report “Exer Action Create Collection”
which is launched in Create mode.
The definition for the report Exer Action Create is same as defined under the section Action-
Create.
Action – Alter
The Alter action also acts upon the Report definition. This action launches the Report in Alter
mode. The Report is invoked in the editable mode where the user can enter values within the
fields. These values are retained within the Tally Database as a part of Internal Object This
action is used when an existing Object is to be updated and persisted in the Tally database.
Example:1
[#Menu: Gateway of Tally]
Add: Key Item: Ledger Alteration: L : Alter: Alter Ledger
[Report: Alter Ledger]
Form : Alter Ledger
Object: Ledger : “ABC Ledger”
;; Object Association done at Report Level

In the example
 Default Menu, Gateway of Tally have been altered to add a new Item Ledger Altera-
tion which allows the user to update an existing Ledger
 Report Alter Ledger is associated with the Ledger Object “ABC ledger” which indi-
cates that the Report is meant for altering the specific ledger Object already existing
in the Tally Database
 The storages for Name and Parent are defined in the same way as taken up in the
“Create Ledger” Report
Example:2

337
Chapter 8 - Object Manipulation & Storage in TDL

In the following example it demonstrates the usage of Alter action at button definition
[Button: My Reco Button]
Key : Alt + F5
Action: Alter: Bank Recon
;; Alter Action to trigger Bank Recon Report in Alter Mode
Title : “Reconcile”

[Form: My Bank Vouchers]


Button: My Reco Button
;; Associating the Button to the Report
 The Button My Reco Button is defined with an alter action to alter the Report Bank
Recon on pressing the Alt + F5 Key. This button is used for entering dates in the
Bank Reconciliation Report.
 The Button My Reco Button is associated to the Form My Bank Vouchers

Exercise 8.2
Objective
The objective of this program is to understand how to manipulate internal object using Field
Attribute 'Alter'.
Capabilities Used
 The Field attribute Alter
 The attribute Key at Line Definition
 The attribute object at report level
Code
[Report: Exer Field Attribute Alter]
Form : Exer Field Attribute Alter
Title : "Field Attribute Alter to alter objects"

[Form: Exer Field Attribute Alter]


Parts : Form SubTitle, Exer FAA Info, Exer Field +
Attribute Alter
Local : Field: Form SubTitle: Info: "Understanding Field+
Attribute 'Alter'"

338
Chapter 8 - Object Manipulation & Storage in TDL

[Part: Exer FAA Info]


Lines : Exer FAA Info

[Line: Exer FAA Info]


Fields: Info Field
Local : Field : Info Field: Info : "Select a Ledger and press+
Enter to alter the desired Ledger Master information"
Local : Field : Info Field: Style: Normal Italic
Local : Field : Info Field: Align : Center
Local : Field : Info Field: FullWidth : Yes
Space Bottom: 1

[Part: Exer Field Attribute Alter]


Lines : Exer FAA Title, Exer FAA Details
Repeat : Exer FAA Details: Exer FAA Ledger
Scroll : Vertical
CommonBorder : Yes

[Line: Exer FAA Title]


Use : Exer FAA Details
Local: Field: Default : Type : String
Local: Field: Default : Align: Center
Local: Field: Default : Style : Normal Bold
Local: Field: Exer FAA Name: Set As : "Name"
Local: Field: Exer FAA Parent : Set As: "Group"
Local: Field: Exer FAA ClosingBalance : Set As:+
"Closing Balance"
Border: Thin Top Bottom

Set As : $Name
;;Variable 'LedgerName' retains the Ledger selected by the user for the subsequent report
Variable: LedgerName

339
Chapter 8 - Object Manipulation & Storage in TDL

[Line: Exer FAA Details]


Fields : Exer FAA Name
Right Fields: Exer FAA Parent, Exer FAA ClosingBalance
Local: Field: Default : Style : Normal
/*The below default Keys act upon Line Definition and the action 'Alter Object' is associated with the Keys provided the
current Report is in Display Mode*/
Key : Line Object Enter Alter, Line Click Object+
Enter Alter
[Field: Exer FAA Name]
;; Field Attribute 'Alter' is used to open the Report 'Ledger' in Alter Mode
Alter : Exer Alter Ledger
FullWidth: Yes

[Field: Exer FAA Parent]


Use : Name Field
Set As: $Parent
Border: Thin Left
Width : 30% Page

[Field: Exer FAA ClosingBalance]


Use : Amount Field
Set As: $ClosingBalance
Border: Thin Left
Width : 15% Page

[Collection: Exer FAA Ledger]


Type : Ledger
Fetch : Name, Parent, ClosingBalance
Filter : Exer FAA NonEmptyCB

340
Chapter 8 - Object Manipulation & Storage in TDL

[Report: Exer Alter Ledger]


;; Default Report 'Ledger' is used to alter the object
Use : Ledger
;; Default Form Ledger
Form : Ledger
;; Object association with Object Identifier for Alter Mode
Object : Ledger: ##LedgerName

[System: Formula]
Exer FAA NonEmptyCB: NOT $$IsEmpty:$ClosingBalance
;; End-of-File

Output

341
Chapter 8 - Object Manipulation & Storage in TDL

Program Explanation
The report Exer Field Attribute Alter is used to alter the ledger objects by using the field
attribute Alter. Two default Keys called Line Object Enter Alter, Line Click Object Enter Alter
are associated to the Line Definition Exer FAA Details that allows a selection of any of the
lines being repeated. Action associated with these Keys is Alter Object which means on hitting
the Key, the Object associated with the current Line must be altered
The attribute Alter is used at Field definition Exer FAA Name invokes the Report “Exer
Alter Ledger” in Alter Mode
The Report Exer Alter Ledger is associated with the Ledger Object, which is in context of the
field Exer FAA Name, and the variable Ledger Name retains the ledger name selected by the
user for the subsequent report Exer Alter Ledger.

Action – Alter Collection


The Action Alter Collection is used to alter an existing Object of Collection thus specified.
The Collection definition in turn specifies the Report to be launched for Altering the Object
ie., the Report specified with the Report Attribute of the Collection is launched in alter mode.

342
Chapter 8 - Object Manipulation & Storage in TDL

For alteration, the Object to be altered needs to be selected from a different Report. This is
specified by using the attribute “Trigger” of the collection.
This action is generally useful for alteration of Masters such as Groups, Ledgers, Stock Items,
Voucher Types, etc.
Example:
;; The following code demonstrates the usage of Alter Collection Action
[#Menu: Gateway of Tally]
Add: Key Item: Ledger Alteration: L: Alter Collection: Ledger Coll
;; Collection definition Ledger Coll
[Collection : Ledger Coll ]
Type : Ledger
Report : Alter Ledger
Trigger : Select Ledger
Variable : Led Name
;;Report Definition “Alter Ledger” associated with the Object Ledger
[Report :Alter Ledger]
Object :Ledger
|
|
;;Trigger Report “Select Ledger” which allows selection of the specific ledger object for alteration in the Report “Alter Ledger”
[Report : Select Ledger]
|
|
;;Field within this report which displays a table of ledgers for selection
[Field: Set My Ledger]
Use : Name Field
Table : Ledger Coll
Show Table : Always
Modifies :LedName
In the example
 The menu item triggers the Action Alter Collection which takes the Collection
“Ledger Coll” as the parameter.
 The collection “Ledger Coll” is a Collection of type ledger. The Report attribute of
the collection specifies the name of the Report “Alter Ledger” which is launched in
Alter mode.

343
Chapter 8 - Object Manipulation & Storage in TDL

 The Trigger attribute of the collection specifies the name of the Report “Select
Ledger” which allows the selection of a particular ledger within the field.
 The field “Set My Ledger” displays a table of ledgers and modifies the value of the
variable “LedName” with the object name selected in the Trigger report
 The Variable attribute in the collection specifies the variable which holds the name
of the Object selected above and subsequently in the Report “Alter Object”

The implementation and usage for the Actions Display Collection and Print
collection is done in the same way as Alter Collection. The Object selected in
the Trigger Report is subsequently displayed or Printed within the main Report
specified with the Report Attribute of the collection..

Action — Modify Object


This is a system Action which is used to update the values of the methods of an Object.
Multiple methods can be altered within the same statement. The syntax allows the specifica-
tion of a value with each method to be updated. Multiple methods of the same object can be
altered by separating the method and value pairs by commas.
Syntax
Modify Object : <PrimaryObjectSpec>.<SubObjectPathSpec>. +
MethodName : Value>[,Method Name: <Value> , …]+
[,<SubObjectPathSpec>.MethodName :<Value>, …..]
The specifications given for <PrimaryObjectSpec>, <SubObjectPathSpec>, MethodName
remain the same as described in the New Method syntax section in the topic Objects and Col-
lection.
Where,
<PrimaryObjectSpec> can be (<Primary Object Type Keyword>, <Primary Object Iden-
tifier Formula>)
<SubObjectPathSpec> is given as CollectionName [<Index Formula>, [<Condition>]]
<MethodName> refers to the name of the method in the specified path.
<Index Formula> should return a number which acts as a position specifier in the Collection
of Objects satisfying the given <condition>
Points to consider while using the Action
 Modify Object supports dotted syntax as in Method Formula Syntax
 In case the Action is triggered with the Primary Data Object in context the specifica-
tion can begin with the Sub Object specification.

344
Chapter 8 - Object Manipulation & Storage in TDL

 In case the Action is triggered from a menu, the primary object specification is man-
datory, as menu will never have a Data Object in context
 A single Modify Object Action cannot modify methods of multiple primary Objects,
but can modify multiple methods of a single Object.
Example:1
[Key: Alter My Object]
Key : Ctrl + Z
Action : Modify Object : (Ledger,"MyLedger").BillAllocations+
[First, $Name="MyBill"].OpeningBalance : 100,+
..Address[Last].Address : "Bangalore"
The existing ledger My Ledger is being altered with new values for the Opening Balance for
the existing bill and Address. The key Alter My Object can be attached to any Menu or Form.
Example:2
[Key: Alter My Object]
Key : Ctrl + Z
Action : Modify Object :(Ledger,"MyLedger").BillAllocations[1] +
.OpeningBalance :1000,Name: ”My New Bill”,..Address[First]+
.Address :"Hongasandra Bangalore" , Opening Balance:5000
The existing ledger My Ledger is being altered with new values for the Opening Balance
applicable on the existing bill, Opening Balance of the ledger and the first line of the Address.
The key Alter My Object can be attached to any Menu or Form.

Example:3
[Key: Alter My Object]
Key : Ctrl + Z
Action : ModifyObject : LedgerEntries[1].BillAllocations[1].Name:+
“Test1”, Amount :“1000.00”, ..BillAllocations[2].+
Name: “Test2”, Amount : “2000.00”, ().Date : “1.4.08”
In a Voucher context, Key Alter My Object alters Name, Amount and Date methods of Sub
object Bill Allocation.
8.1.4 Action Modify Object in a Menu Definition
A button Alter My Object is added within the menu definition

345
Chapter 8 - Object Manipulation & Storage in TDL

[#Menu : Gateway of Tally]


Add : Button : Alter My Object
The following points should be considered while associating a key with the action Modify
Object at the menu level:
 Since the Menu does not have any Data Objects in context, specifying Primary
Object becomes mandatory
 Since the Menu cannot work on scopes like Selected, Unselected, etc. the scopes
spec¬ified are ignored
 Any formula specified in the value is evaluated assumes the Menu Object as the
requestor
 Even Method values pertaining to Company Objects can be modified
 A button can be added in the Menu to specify the action Modify Object at the Menu
level
Example for Action – Modify Object
Let us learn how to use the Action-Modify Object
Exercise 8.3
Objective
The objective of this program is to understand how to alter Internal Objects using Action
Modify Object
Capabilities Used
 Usage of the action Modify Object
 The usage of Function Definition
 The Variable declaration and usage of Variable inside function
 Function $$AsAmount
Code
[Function: Exer Action Modify Object]
Variable : SLedger: String
00: MSGBOX: "Modify Object": "This code modifies the \n Method+
Opening Balance of Ledger Cash to 150000"
;; Action 'Modify Object' is used to modify the Opening Balance of Ledger 'Cash' to 150000
10: MODIFY OBJECT: (Ledger, "Cash").OpeningBalance: ($$AsAmount:+
"150000")
/*Subsequent to modification, the same is displayed to the user using Action 'Display' which displays the default Report
'Ledger' which uses Variable 'SLedger' as its Object identifier, hence setting the value to this variable prior to displaying
the Report 'Ledger'*/

346
Chapter 8 - Object Manipulation & Storage in TDL

20: SET : SLedger: "Cash"


30: DISPLAY: Ledger
;; End-of-File
Output

347
Chapter 8 - Object Manipulation & Storage in TDL

Program Explanation
The user defined function Exer Action Modify Object is used to modify the opening balance
of the ledger “cash” to 150000 by using the action Modify Object and it displayed a message
by using the action MSGBOX.
Further, the action SET is used to set the value of the variable SLedger. The variable SLedger
is used as an object identifier for the subsequent default report “Ledger”. The action Display is
used to display the report “Ledger” with the object “cash” which is associated at the report
level.

Action – Set Object Values


The action Set Object Values is similar to the action modify object. This action works only in
the Edit mode of a Report as it uses current data object in context. This action changes the
values of the object from current context as specified. This also accepts a comma separated list
of method name and value pairs.

348
Chapter 8 - Object Manipulation & Storage in TDL

Syntax
Action: Set Object Values: <SubObjectPathSpec>.<Method Name>:+
<Method Value>

Where,
<SubObjectPathSpec> is given as CollectionName [<Index Formula>, [<Condition>]]
<MethodName> refers to the name of the method in the specified path and
<Method Value> is the value to be set for the <Method Name>.

Example:
[Key : My Key]
Action : Set Object Values : Opening Balance : ($$AsAmount : 10)
This action alters the current object in memory. When the Primary object is saved the changes
will be updated in Tally database.

8.2 Object Manipulation using TDL/User Defined Functions (Procedural


Capabilities)
Procedural capabilities have been incorporated into the language using TDL/User Defined
functions. One of the major breakthrough with this is the capability on Object Manipulation
i.e., Creation and Alteration of Internal Data Objects.
An expression in TDL is always evaluated in context of the Interface (Requestor) and the Data
Object Associated with the Interface object. This is referred to as Current Object context.
Whenever an Inbuilt function is referred it will be evaluated with current Data and Requestor
Object in context. Since TDL function will be performing some manipulations on data, it will
require another Object in context. The object which is being populated or altered is referred as
the Target object. Apart from Current object context another context is available within TDL/
User Defined Function which is referred to as Target Object Context. It is possible to obtain
the values from caller object context and alter the values of the target object with those values.
There are various Actions introduced specifically for usage within User Defined Functions for
Object and Context Manipulation. The various operations which can be performed while per-
forming Object manipulations are listed as below
 Adding a new Object
 Adding a new sub collection object to an Object
 Updating the methods of an Object
 Saving an Object
 Looping over and existing Collection
 Switching context between Current and Target Object

349
Chapter 8 - Object Manipulation & Storage in TDL

We will be taking up the detailed explanation and usage of these Actions and
Object Manipulation as a whole in the subsequent chapter on TDL procedural
Capabilities

8.3 Object Manipulation using Data gathered from External Data Sources
To meet the challenges of business environment it becomes absolutely mandatory to share
information seamlessly across applications. Integration becomes a crucial factor in avoiding
the duplication of data entry. There are many interfaces through which the applications can
integrate. Different applications use different interfaces for communicating with each other.
Examples of interfaces are ODBC, XML, SOAP, DLL etc.
We have already seen in the previous chapter that, data available over these interfaces can be
gathered for further processing into a Collection. Subsequently, this can be stored as an
Internal Object and form an integral part of the Tally Database either through a Report or using
the data manipulation capabilities of TDL/User Defined Functions.
Data available in SDF format can be imported in Tally by defining the file structure using
“Import File” definition and mapped to the an Internal Object using the “Import Object” defi-
nition.
Syntax
Storage at Import Object Definition
Storage : Storage Name : #FieldName
Example:
[!Import File: Ledger Import]
Repeat : #ImpLedName
Field : ImpLedName : 30
Field : ImpLedGroup : 30
Field : ImpLedOpBal : 15
Field : ImpSVStatus : 2
Field : CRLF : 2
;; Carriage Return Line Field
Object: LedgerObj
Empty : #SVStatus = "P"

350
Chapter 8 - Object Manipulation & Storage in TDL

In the example an Import File is created where the fields are defined with the specified width.
The corresponding Import Object definition associates the Object Ledger using the Object
attribute. The storage attribute is used to map the fields with the corresponding method/storage
names.
[Import Object: LedgerObj]
Object : Ledger
;; Ledger is an internal object.
Storage : Name : #ImpLedName
Storage : Parent : #ImpLedGroup
Storage : OpeningBalance : #ImpLedOpBal

For the detailed usage and examples refer the book “Tally.ERP 9 – Integration
Capabilities”

351
Chapter 9: TDL Procedural
Capabilities

9.1 Introduction
When we talk in general, from any programming language point of view there are Procedures
and Functions which are used to perform any Action either by returning a value or not. Proce-
dures are a fixed set of statements that are executed sequentially to perform a task. The same
task might be performed repetitively. Subroutines are procedures which are executed repeat-
edly. Generally subroutines are called from the main program. Procedures can accept zero or
more parameters as input to perform the specified operation. Some procedures which return a
value to the calling environment are generally referred as Functions.
As we already know, TDL is basically a non procedural language which allows the programmer
to specify the actions required to perform a task. The sequence in which these Actions get
triggered is purely based on user interaction. The Actions in turn act upon a particular defini-
tion. In TDL procedural capabilities are added with the introduction of a definition “Function”.
The fundamental aspects of conditional evaluation and looping have been introduced into the
language. The various procedural elements can be used for flow control, computation and
object data manipulation.
When a function is used to perform a specified task without returning a value, it can be
triggered as an “Action” on the occurrence of a System or User Driven event. When the
function is created primarily with an objective of achieving some computation result, it can be
referred from a field or an expression in the same way as In Built/Platform defined Functions.

9.2 Functions – In TDL


TDL language has a comprehensive set of built-in TDL functions written for specific business
requirement. These are referred as In built/Platform defined Functions which can be used by
the application developer.

Please refer to function browser provided along with Tally Developer 9 for a
detailed documentation on built in functions

353
TDL Procedural Capabilities

With the introduction of the definition Function, programmer has the capability to create
Functions as per his requirements and trigger it as an Action or as an In built function. We will
be referring to Functions created by the programmer as TDL/User Defined Functions.
The functions in TDL can be broadly classified into two categories:
1. In Built/Platform Defined Functions
2. TDL/User Defined Functions

TDL procedures may depend upon/call platform functions to perform some specific task. If a
function with the same name exists in the default TDL source code then the In Built functions
always take precedence over the user defined functions.

9.2.1 In Built/Platform Defined Functions


Platform Functions are functions predefined by the platform in order to accomplish a specific
task. A wide range of functions are available in the TDL functions library for varied purposes
like business related, mathematical, string etc. The application developer has no control over
the execution sequence of these functions. They can only be used as and when required to
achieve their specific task. Some functions may not require any parameters like $$NewLine
which moves to the next line. Some functions may require one or more parameters; depending
on the design of the Function e.g. $$Inwords accepts one parameter of amount type and
returns the amount in words.

9.2.2 User Defined TDL Procedures/Functions


TDL Functions are action statements defined by an application developer. The developer has a
complete control over the sequence in which these actions get executed.
 A TDL function extends the following benefits to the TDL programmer:
 To perform a set of actions sequentially with or without any conditional statements.
 Allows looping and conditional execution of a set of actions
 Defining once and executing it repetitively passing different set of parameters
 To define variables, manipulate and set values in it
 To work on data elements like getting an object context from the calling UI, chang-
ing the context, looping the objects of a collection, reading data from source and set-
ting value in the target object, etc.
 Creation and Manipulations of the existing Internal Objects
With the advent of TDL the application developer can write complex business functions ease
and without much platform dependency.

354
TDL Procedural Capabilities

In TDL, the definition type Function is used to create functions. Let take a look at the function
definition which is used to calculate the simple interest. It accepts three parameters as princi-
ple, rate and time period.

[Function: SI Calc]
;; Definition Block
Parameter: P : Amount
Parameter: R : Number
Parameter: T : Number
Returns : Amount
Variable : Interest: Amount
;; Procedural Block
01 : SET : Interest: (##P * ##R * ##T) / 100
02 : RETURN: ##Interest

The function definition is divided in two blocks viz. Definition and Procedural. The valid
statement in each block will be discussed in detail in the section ‘Function - Building Blocks’.
We have partly discussed on how a Function can be called as Actions in the chapter on
Actions. We will cover this in detail in the following section.

Calling a Function
Basically a Function is created with two purposes:

1.To be used as an Action performing a particular set of tasks without returning a value
The action thus created can be triggered on the occurrence of a System Driven/User Driven
Event.
For handling User Driven Events the Action can be associated at:
 Key/Button Definition using the Action attribute
 Menu Definition along with a Menu Item
 Field Definition using the Action keyword
For handling System Driven Events the Action can be associated at:
 System: Event definition using the Event keyword provided
 Specific definition level using the On attribute and Event Keyword

355
TDL Procedural Capabilities

Using the keyword CALL


An Action created by programmer using the “Function” definition has to be called using the
keyword “CALL”
Syntax
CALL : <Function Name> [ :<Parameter List>]
Where,
<Function Name> is the name of a user defined function
<Parameter List> is the list of parameters required by the function to perform the specified
task successfully. It’s optional.

Example:Calling a Function using CALL

[#Menu: Gateway of Tally]


Button : Call Function

[Button : Call Function]


Key : Alt + F9
Title : “Call Function”
Action : Call : DispStaturoryRpts

2.To be used as a Function performing some complex computation and returning the
value/result to the calling program
In such cases the Function will be called from a field or an expression where certain values
will be passed from the caller context to the function. The function performs some computa-
tions and returns the result/value to the calling field/expression.

Using - Symbol Prefix $$


When the function returns a value, it can be used within a value expression by prefixing it with
access specifier $$. The value returned by the function is can be used in the value expression
of the calling program or as a value for Set As attribute of the field.
Syntax
$$<FunctionName> [ :<Parameter List>]
Where,
<Function Name> is the name of a user defined function

356
TDL Procedural Capabilities

<Parameter List> is the list of parameters required by the procedure to perform the specified
task successfully. It’s optional.
Example:Calling the function at Field using $$
[Field: Call Function]
Use : Number Field
Set as : $$FactorialOf:#InputFld

The action CALL allows the spaces in function name where as if $$ is used then
the spaces are not allowed in the function name.

Passing Parameters
As explained earlier, the TDL Function may require some input from the calling environment
to perform the specified operation. The number of parameters required to be passed to the
function depends on the number of Parameters declared in the function definition. A default
value can be specified for the parameters. These parameters are considered as optional i.e.
while calling the function the values passed for this parameter is optional
The parameters can be passed as expressions to the function while invoking it. While calling
the procedure or function the parameters are separated by “:”. If less number of parameters are
passed then the remaining parameters must be defined as option parameter in the function def-
inition. If the number of parameters that are passed is more than the required parameters then
the remaining parameters are treated as a single value for the last parameter.
For eg: If a function takes three parameters, it is possible to pass only one or two parameters
while calling the functions, if default values for those parameters are specified inside the
function declaration.

Example:The function SICalc accepts three parameters but is a can be called as follows:
[Field : Simple Interest]
Set As : $$SICalc:#InterestPrincipal:#InterestRate

The value for the last parameter is specified in the declaration itself.
For e.g.: If a function takes three parameters and while calling if more than three parameters
are passed then, after considering values for two parameters, all the successive values
separated by colon are taken as third parameter.

357
TDL Procedural Capabilities

Example:The function SICalc accepts three parameters but is a can be called as follows:

[Field : Simple Interest]


Set As : $$SICalc:#InterestPrincipal:#InterestRate:+
#InterestNoOfYrs:#Period
The parameters #InterestNoOfYrs:#Period are considered as the value of the last parameter.

A function with parameter cannot be called directly from a Menu.

After understanding the TDL procedure overview, now let’s understand the various statements
in the Function definition.
9.3 Function – Building Blocks
As explained earlier, the TDL functions are defined using the definition type Function. All the
statements specified in the function definition are implemented as Predefined Actions. We will
be referring to them as programming constructs and statements as per generic programming
norms.
The Function definition is divided in two blocks viz. Definition Block and Procedural Block.
Let’s take a glimpse on the structure of a Function.

[Function : Function Name]


;; Definition Block
;; Parameter Specification
Parameter: Parameter1: Datatype
Parameter: Parameter2: Datatype
;; Variable Declaration
Variable : Var 1: Number
Variable : Var 2: String
;; Explicit Object Association
Object : ObjName: ObjectType
;; Local Formula Specification
Local Formula : <expression>
;; Return Type Specification

358
TDL Procedural Capabilities

Returns : DataType
;; Procedural Block
Label 1 : Statement 1
Label 2 : Statement 2
|
Label n : Statement n
Definition Block
The definition Block is utilized for declaring various components that the TDL procedure will
require to perform the Tasks. The parameter, variable, object, local formulae and the return
data type are specified in this block. The definition block is followed by Procedural block in
which all the procedural statements are specified to perform the task.

Parameter Declaration
This is used to declare the list of parameters to be passed while calling code. The values
passed to the function are referred with these variable names inside the function. The attribute
Parameter of Function definition is used for specifying the parameters. The attribute Parameter
is of type Dual List.
Syntax
PARAMETER : <Variable Name> : <Data Type of the Variable>
Where,
<Variable Name> is the name of the Variable which holds the parameter sent while calling
the TDL procedure.
<Data Type of the Variable> is the Data type of the Variable sent while calling the TDL pro-
cedure.

Example:The Function ‘FactorialOf’ receives number as parameter from the Caller.


[Function : FactorialOf]
Parameter : InputNumber : Number
Variable Declaration
The TDL procedure may require some variables for intermediate calculation; these variables
can be defined using the attributes Variable, List Variable and Static Variable. The scope of
these variables is within the TDL function and looses its value on exit. The scope extends to
the Menu, Reports and TDL functions called from TDL procedure. The variables can also be
declared with default value. The variables defined inside the TDL Procedure will never inherit
the value from the parent context. This means that a volatile attribute on function variables has
no effect. Function allows actions to change the value of the variables.

359
TDL Procedural Capabilities

Syntax
VARIABLE : <Variable Names> [:<Data Type> [: <Value>]
Where,
<Variable Names> is the comma separated list of Simple or Compound Variables.
<Data Type> is an optional parameter to specify the data type of Simple Variable. If the data
type is specified, then it is called Inline declaration of variable. In case of Compound Variable,
data type cannot be specified here as it consists of members belonging to various data types. If
the data type is not mentioned, the primary variable definition is mandatory.
<Value> is an optional parameter used to specify the default/initial value provided for the
variable.
Example:The TDL procedure ‘FactorialOf’ requires intermediate Variables ‘Counter’
and ‘Factorial’ for calculation within the Function Definition.

[Function: FactorialOf]
Parameter : InputNumber : Number
Variable : Counter : Number
Variable : Factorial : Number

List Variable Declaration


The attribute List Variable is used to specify a list of either a Simple or Compound Variable.
Syntax
List Variable: <Variable Names> [:<Data Type>[:<Value>]]
Where,
<Variable Names> is the comma separated list of Simple or Compound Variables.
<Data Type> is an optional parameter to specify the data type of Simple Variable. In case of
Compound Variable, data type cannot be specified here as it consists of members belonging to
various data types. If the data type is not mentioned, the primary variable definition is manda-
tory.
<Value> is an optional parameter used to specify the default/initial value provided for the
variable.

If the data type is specified, then it is called Inline declaration of variable.


Example:
To print all Ledgers with Index Page

360
TDL Procedural Capabilities

[Function: All Ledgers with Index]


List Variable: Index Page: Number

Variable : IsMultiPage: Logical


Variable : InNewPages : Logical
Variable : DSPGodownName: String
In the example, a list variable IndexPage is defined in addition to simple variables.

Static Variable Declaration


Static Variable is a Variable, whose value persists between successive calls to a TDL proce-
dure. The scope of the static variable is limited to the TDL function where it is declared and
exists for the entire session. A static variables declared in a TDL function are equivalent to a
system variables but can be accessed only within the defined TDL function. Their initial
values are set only during the first call to the TDL function, and later it retains the value for
further calls.
Only simple or compound variables can be declared as static. List variables are not currently
supported at static scope.

Syntax
STATIC VARIABLE :<Variable Name> [:<Data Type of the Variable>]
Where,
<Variable Name> is the name of the Static Variable
<Data Type> is an optional parameter to specify the data type of Simple Variable. In case of
Compound Variable, data type cannot be specified here as it consists of members belonging to
various data types. If the data type is not mentioned, the primary variable definition is manda-
tory.
Example:
The static variable ‘Sample Static Var’ retains the value between successive calls to TDL
procedure ‘Static Var in Func’
[Function: Static Var in Func]
Static Variable : Sample Static Var : Number

Object Specification
TDL procedure will inherit the Object context of the caller. This can be overridden by using
the attribute Object for function definition. This now becomes the current object for the TDL
function.

361
TDL Procedural Capabilities

Syntax
Object: <Object Type> : <Object Identifier>
Where,
<Object Type> is the type of the object
<Object Identifier> is the unique identifier of the object
Example:
The current Object context for the TDL function ‘Sample Function’ is the Ledger ‘Party’
[Function: Sample Function]
Object : Ledger : “Party”

Local Formula Specification


In the scenarios where complex expressions are written in the TDL function, Local Formulae
can be used for enhanced readability of code. The attribute Local Formula is used to specify a
local formula within the function block. It is a Dual List type attribute which accepts the
formula name and its value as a parameter.
Syntax
Local Formula : <Formula Name> : <Value>
Where,
<Formula Name> is name of the formula
<Value> is to specify of the formula

Example:
[Function: LV Index Based Retrieval]
Local Formula: Total List Items : $$ListCount:LVEmpIndex

Return Value Specification


If a Function returns a value to the caller, then its data type is specified by using ‘RETURN’
statement. RETURNS is an alias for the attribute RETURN.
Syntax
RETURN: <Data Type of the Return Value>

Where,
<Data Type of the Return Value > is the Data type of the return value of the Function

362
TDL Procedural Capabilities

Example:
The Function ‘FactorialOf’ returns value of type ‘Number’ to the caller of the Function
[Function: FactorialOf]
Parameter : InputNumber : Number
Return : Number
Variable : Counter : Number
Variable : Factorial : Number
9.3.1 Procedural Block
This block contains a set of statements. These statements can either be a programming
construct or can be an Action specification. Every statement inside the procedural block has to
be uniquely identified by a label specification.The programming constructs are implemented
internally as Actions Only.

LABEL SPECIFICATION : Programming Construct


Or
LABEL SPECIFICATION : Action keyword : Action Parameter
Example:
The Function ‘DispStockSummary’ is having two Actions with Label.
[Function: DispStockSummary]
01 : Display : Stock Summary
02 : Display : Stock Category Summary

9.4 Function Execution – Object Context


An expression in TDL is always evaluated in context of the Interface (Requestor) and the Data
Object Associated with the Interface object. This is referred to as Current Object context.
Whenever an Inbuilt function is referred it will be evaluated with current Data and Requestor
Object in context. Since TDL function will be performing some manipulations on data, it will
require another Object in context. The object which is being populated or altered is referred as
the Target object.
9.4.1 Target Object Context
Target Context mainly refers to the object context which can be set inside the TDL function
which allows performing manipulation operations for that object i.e. alteration and creation.
The object context of the caller and target object context can be different. It will now be
possible to obtain the values from caller object context and alter the values of the target object
with those values.

363
TDL Procedural Capabilities

User has option to override the context within the TDL function later or use the same context
being passed. He can change the current and target object at any point and also switch target
and current object with each other.
9.4.2 Parameter Evaluation Context
It is important to note that the parameter values which are passed to the TDL function are
always evaluated in context of the caller. Parameter declaration within the TDL function is just
to determine the data type, order and no of parameters. These are basically the placeholders for
values passed from caller object context. The target object context or context switch within the
TDL procedure does not affect the initial values of the parameters. Later within the TDL
procedure these values can be altered just like ordinary variables.
9.4.3 Return Value Evaluation
We have already discussed above that TDL function can return a value. This can be specified
by the TDL function by indicating the data type of the value it returns, no specification
assumed as a void TDL function (a TDL procedure / function which does not return a value).
Each statement used can return a value. This depends on the individual action. Some actions
may not return value. The data type of return value is also predefined by the action. Return
value of the last action executed can be extracted using an internal function ‘$$LastResult’.
Any error messages generated from the system can be obtained with $$LastError. This can
only be used to determine the result of the intermediate statements used within the TDL
function. The final value which is to be returned from the TDL function has to be explicitly
given using the RETURN attribute.

Function – $$TgtObject
The Context Evaluation function $$TgtObject evaluates the expression in the context of the
Target Object. Using the $$TgtObject values can be fetched from the target object without
making the target object as the current context object.
Syntax
$$TgtObject:<String Expression>
Where,
<String Expression> the expression and will be evaluated in the context of Target Object

Example:
The Ledgers Party 1 and Party 2 having some opening balance. The requirement is to add the
opening balance of both the party’s and set the resultant value as the opening balance of Party
2.
[Function: Sample Function]
Object : Ledger : "Party 1"

364
TDL Procedural Capabilities

01 : NEW OBJECT : Ledger : "Party 2"


02 : SET VALUE : OpeningBalance : $OpeningBalance +
$$TgtObject:$OpeningBalance
03 : ACCEPT ALTER

Here Party 1 is the source object and Party 2 is the target object. The opening balance of
Party 2 is accessed using the $$TgtObject:$OpeningBalance.

Valid Statements – Inside Functions


All the valid statements used within the procedural block can be categorized as below
 Programming Constructs
Conditional Constructs

Looping Constructs

Control Constructs

 Actions
System Actions

Object and Context Manipulation Actions

User Interface Actions

Debugging Actions

File I/O Actions

9.4.4 Programming Constructs


In TDL following conditional constructs are provided to control the flow of execution:
 IF - ENDIF
 IF - ELSE - ENDIF
 DO - IF
IF – ENDIF
The IF - ENDIF statement is a powerful decision making statement and is used to control the
flow of execution of statements. It is basically two-way decision statement and is used in con-
junction with an expression. Initially expression will be evaluated and based on the whether
expression is true or false, it transfers the execution flow to a particular statement.

365
TDL Procedural Capabilities

Syntax
IF : <Condition Expression>
STATEMENT 1
|
|
STATEMENT N
ENDIF
Where,
<Condition Exprn> is an expression which returns a logical value. If it is TRUE then the
specified statements are executed.

Example:
Lets take the example of writing a function code to calculate the factorial of the given number.
In the code we have to validate that the argument passed is a positive number. If Function
parameter sent to Function ‘FactorialOf’ is less than zero then it is multi-plied by -1 to find the
absolute value.
[Function: FactorialOf]
|
3 : IF ##InputNumber < 0
4 : SET : InputNumber: ##InputNumber * -1
5 : END IF

366
TDL Procedural Capabilities

IF – ELSE – ENDIF
The IF – ELSE –ENDIF statement is an extension of the simple IF-ENDIF statement. If
condition expression is true, then true block statement(s) are executed; otherwise the false
block state¬ment(s) are executed. In either case, either true block or false block will be
executed, not both.

Syntax
IF : <Condition Expression>
STATEMENT 1
|
|
STATEMENT N
ELSE
STATEMENT 1
|
STATEMENT M
ENDIF

Where,
<Condition Exprn> is an expression which returns a logical value. If it is TRUE then the
specified statements 1- N are executed other wise the statements 1 to M are executed.

367
TDL Procedural Capabilities

Example:
Consider the following code snippet to find greatest of three numbers passed as parameters to
the function ‘FindGreatestNumbers’.

[Function: FindGreatestNumbers]
|
01 : IF: ##A > ##B
02 : IF : ##A > ##C
03 : RETURN : ##A
04 : ELSE
05 : RETURN : ##C
06 : END IF
07 : ELSE
08 : IF : ##B > ##C
09 : RETURN : ##B
10 : ELSE
11 : RETURN : ##C
12 : END IF
13 : END IF

DO – IF
When a IF - ENDIF statement block contains only one statement, then the same can be written
in single line by using DO-IF statement.
Syntax
DO IF: <Condition Exprn> : <Action Keyword> : +
<Action Parameter>
Where,
<Condition Exprn> is an expression which returns a logical value. If it is TRUE then the
specified action is executed.
<Action Keyword> is any one of the valid statement/actions.
<Action Parameters> parameters of the actions specified

368
TDL Procedural Capabilities

Example:
Let’s take the same example of writing a function code to calculate the factorial of the given
number. If Function parameter sent to Function ‘FactorialOf’ is less than zero then it is
multi¬plied by -1 to find the absolute value. IF - END IF statement is re written using DO - IF
statement.

[Function: FactorialOf]
|
3: DO IF : ##InputNumber < 0 : ##InputNumber * -1
Most programming languages have constructions for repeating a loop until some condition
changes. A loop is a sequence of statements which is specified once but which may be carried
out several times in succession.
In looping, a sequence of statements is executed until some conditions for termination of the
loop are satisfied. A typical loop consists of two segments, one known as the body of the loop
and the other known as the control statement. The control statement checks condition and then
directs the repeated execution of the statements contained in the body of the loop.
There are variations of the loops based on the way the control statement is executed. In some
the condition is evaluated at the start of the loop, while others have the test at the end of the
loop. In the former case the body may be skipped completely, while in the latter case the body
is always executed at least once.
TDL allows following looping constructs for varied usage:
 WHILE – END WHILE
 FOR RANGE – END FOR
 FOR TOKEN – END FOR
 WALK COLLECTION – END WALK
 FOR COLLECTION – END FOR
 FOR IN/FOR EACH – END FOR

The looping can be done on the objects in collection, on the tokenized string, for a range of
values and condition based looping of a set of statement. Lets understand the usage of each
loop in depth.
WHILE – ENDWHILE
The WHILE – ENDWHILE is an entry controlled loop statement. The condition expression is
evaluated and if the condition is true, then the body of the loop is executed. After the execution
of the statements within the body, the condition expression is once again evaluated and if it is
true, the body is executed once again. This process of repeated execution of the body
continues until the condition expression finally becomes False and the control is transferred
out of the loop.

369
TDL Procedural Capabilities

Syntax
WHILE : <Condition Expression>
STATEMENT 1
|
STATEMENT N
ENDWHILE
Where,
<Condition Exprn> is an expression which returns a logical value. If it is TRUE then only the
specified statements 1- N are executed.
Example:
Let’s consider the same example of writing a function code to calculate the factorial of the
given number. The same function can be rewritten by using WHILE – ENDWHILE looping
construct. The Function ‘FactorialOf’ repeats statements 4 and 5 till given condition is satis-
fied.
[Function: FactorialOf]
|
3: WHILE : ##Counter <= ##InputNumber
4: SET : Factorial : ##Factorial * ##Counter
5: SET : Counter : ##Counter + 1
6: END WHILE
|
Exercise 9.1:
Objective
The objective of this program is to find the Exponentiation i.e. Nth Power of a Number using
TDL Procedural Capabilities (User Defined Function).
Capabilities Used
 The procedural capability of TDL is used to calculate the Nth Power of a Number.
 The Base number and the Exponent are passed as parameter to the user defined func-
tion which returns the calculated value to the calling field.
 The field attribute Set Always is used to refresh the value in the field each time the
values in the fields it refers to are changed.

370
TDL Procedural Capabilities

Code
[Report: Exer Proc Powerof]
Form : Exer Proc Powerof
Title : "Calculate Power of a Number"

[Form: Exer Proc Powerof]


Parts: Form SubTitle, Exer Proc Powerof
Local: Field: Form SubTitle : Info : "Calculate Power of a Number"
Width: 25% Page

[Part: Exer Proc Powerof]


Lines: Exer Proc PO Base, Exer Proc PO PowerOf, Exer Proc PO Result

[Line: Exer Proc PO Base]


Fields : Medium Prompt, Exer Proc PO Base
Local : Field: Medium Prompt: Set As : "Enter Base Number :"

[Field: Exer Proc PO Base]


Use : Number Field

[Line: Exer Proc PO PowerOf]


Fields : Medium Prompt, Exer Proc PO PowerOf
Local : Field: Medium Prompt: Set As : "Enter Power of Factor :"

[Field: Exer Proc PO PowerOf]


Use : Number Field

[Line: Exer Proc PO Result]


Fields : Medium Prompt, Exer Proc PO Result
Local : Field: Medium Prompt: Set As : if @@ExerNonEmptyFields+
then "Result (" + $$String:#ExerProcPOBase + " ^ " +
$$String:#ExerProcPOPowerOf + ") =" else "Result ="
SpaceTop: 1

371
TDL Procedural Capabilities

[Field: Exer Proc PO Result]


Use : Number Field
/* Invoking the User Defined Function with the above Field Values as Parameters to the Function and setting the return
value to the Field.*/
Set As: if @@ExerNonEmptyFields then $$ExerProcPOC-
alc:#ExerProcPOBase:#ExerProcPOPowerOf else 0
Format: "NoZero"
Read Only: Yes
Set Always: Yes
[System: Formula]
Exer NonEmptyFields : NOT ($$IsEmpty:#ExerProcPOBase OR +
$$IsEmpty:#ExerProcPOPowerOf)
;; Function definedto calculate the Power of the given number
[Function: ExerProcPOCalc]
Parameter: pBaseValue: Number
Parameter: pPowerOf : Number
Variable : Result : Number: 1
/* 'WHILE' is a looping construct which executes the loop for as many times till
the condition '##pPowerOf > 0' is satisfied*/
00 : WHILE : ##pPowerOf > 0
10 : SET : Result: ##Result * ##pBaseValue
20 : DECREMENT: pPowerOf
30 : END WHILE
;; This value will be returned to the calling Field
40 : RETURN: ##Result
;;End-of-file

372
TDL Procedural Capabilities

Output

Program Explanation
The report displays fields to accept the number and power of factor respectively. The resultant
Exponentiation is displayed in the Result field. The field Exer Proc PO Result calls the
function ExerProcPOCalc. The values of the field ExerProcPOBase and ExerProcPOPow-
erOf are passed to the function ExerProcPOCalc.
The function ExerProcPOCalc uses TDL procedural constructs Parameter, Variable,
Decrement and the looping construct WHILE for the calculating the Exponentiation of the
given number. The WHILE loop is executed till the value of the parameter “pPowerof “ is
greater than zero. The action SET is used to modify the value of the variable “Result” with the
product of previous value and the Base. The action RETURN is used to return the computed
value to the calling field.
In the field Exer Proc PO Result attribute Set Always is used to refresh the value whenever
the values in the fields ExerProcPOBase and “ExerProcPOPowerOf” are changed.

FOR RANGE – END FOR


When the looping is to be performed for a range of values, the loop construct FOR RANGE is
used.

373
TDL Procedural Capabilities

The FOR RANGE loop allows repeating a loop for the given range of numbers or date values.
The range can either be incremental or decremental.
Syntax
FOR RANGE: <Iterator Var> : <Data type> : <StartRangeExpr> : +
<EndRangeExpr> [: <Increment Expr> [:+
<DateRangeKeyword>]]
STATEMENT 1
|
STATEMENT N
END FOR
Where,
<Iterator Var Name> is the name of variable used for the iteration. This variable is created
implicitly.
<Data Type> can be Number or Date only.
<StartRangeExpr> is an expression which evaluates to number or date values. It refers to the
starting value of the range.
<EndRangeExpr> is an expression which evaluates to number or date values. It refers to the
end value of the range.
<Increment Expr> is an expression which evaluates to number by which the <StartRange-
Expr> value is incremented. It’s optional and the default value is one.
<DateRangeKeyword> is optional and only applicable if the data type is Date. The values
can be any one of ‘Day’, ‘Week’, ‘Month’ and ‘Year’.
Example:
|
01: FOR RANGE : IteratorVar : Number : 2 : 10 : 2
02: LIST ADD : EvenNo : ##IteratorVar
03: END FOR
|
The values 2,4,6,8,10 are added in the List variable ‘EvenNo’ as the range of value i.e. 2 to 10
and the value is incremented by two with each iteration.
Example:
The following code snippet is used to calculate the number of weeks elapsed between System
date and Current Date set in Tally.
|
09 : FOR RANGE : IteratorVar : Date: ##SVCurrentDate : +

374
TDL Procedural Capabilities

$$MachineDate : 1 : "Week"
10 : LOG : ##IteratorVar
20 : INCREMENT : Cnt
30 : END FOR
50 : LOG : “No of weeks Back Dated :” + $$String: ##Cnt
60 : RETURN: ##Cnt
|
Assume that the range for this is 15 – Mar – 2009 to 30 – Mar – 2009. The values 15-Mar-
2009, 22-Mar-2009 and 29-Mar-2009 are logged as the increment is done by a ‘Week’ so there
are three iterations of the loop. The number of weeks is logged using the counter.
Example:
|
09 : FOR RANGE : IteratorVar : Date: ##SVFromDate : ##SVToDate :+
1 : "Month"
10 : LOG : $$MonthEnd:##IteratorVar
20 : END FOR
|
Assume that the range for this is 1 – Jan – 2009 to 5 – Mar – 2009. The values 31 – Jan -2009,
28 – Feb – 2009 and 31 –Mar -2009 are logged.

FOR TOKEN – END FOR


Another looping construct is supported to loop on the String expression separated by a
delimiter character. It is used to loop on a String expression and returns one value at a time.
The value is returned through iterator variable.
Syntax
FOR TOKEN : <IteratorVar> : <Src String Exprn> +
[: <Delimiter Char> : <Bracket Flag>]
STATEMENT 1
|
STATEMENT N
END FOR

375
TDL Procedural Capabilities

Where,
<Iterator Var Name> is the name of variable user for the iteration. This variable is created
implicitly.
<Src String Exprn> can be any string expression separated by a <Delimiter Char>.
<Delimiter Char> can be any expression which evaluates into a character used for separating
string expression. The default separator char is ‘:’.
<Bracket Flag> is used to consider brackets while deciding the separator character.

Example:
[Function : Test Function]
|
01: FOR TOKEN : TokenVar : "Tally:Shopper :Tally Developer" : +
":" : FALSE
02: LOG : ##TokenVar
03: END FOR
The above code snippet will give the output as shown below:
Tally
Shopper
Tally Developer

WALK COLLECTION – END WALK


The core design principle of Tally.ERP 9/ TDL revolves around Objects and Collection. So
while writing the TDL functions, a set of statements needs to be executed for each object of
the collection. The loop WALK COLLECTION controls the iteration of a loop based on the
number of objects in a collection.
If a Collection has ‘n’ Objects then WALK COLLECTION – ENDWALK will be repeated for
‘n’ times. Body of the loop is executed for each object in the collection, making it the current
context.
Syntax
WALK COLLECTION : <Expression> [: <Rev Flag> ]
STATEMENT 1
|
STATEMENT N
ENDWALK

376
TDL Procedural Capabilities

Where,
<Expression> can be any expression which evaluates to collection name.
<Rev Flag> can be an expression which evaluates to logical value. If it is True then the collec-
tion objects are traversed in reverse order. This parameter is optional. The Default value is
False.
Example:
Walking over all the Vouchers and counting the same
[Function: Count Vouchers]
|
002: WALK COLLECTION : Vouchers Coll
003: SET : Count : ##Count + 1
004: END WALK
|
Example:
[Function : Test Function]
Parameter : parmcoll
|
05 : WALK COLLECTION : ##parmColl : Yes

The collection name is passed as a parameter to the function ‘Test function’ and it is walked in
reverse order.
The code snippet to call the function ‘Test function’ from a key is as shown:

[Key: DC Call Function]


Key : Enter
Action : CALL : Test Function :##CollName
The collection name is passed through the variable ‘CollName’.

FOR COLLECTION – END FOR


When WALK COLLECTION is used then the object of collection is set as the current object
in the context of iteration. i.e., the loop is executed for each object in the collection, making it
as the current context.

377
TDL Procedural Capabilities

The looping construct FOR COLLECTION provides a context free walk since the collection
object is not set as current object context while looping. It loops on the collection for the
specific value and returns the value in the iterator variable. The value of iterator variable can
be referred by the actions inside the FOR COLLECTION loop.
Syntax
FOR COLLECTION : <IteratorVar> : <Coll Exprn>[:+
<Value Exprn: <Rev Flag> ]
STATEMENT 1
|
STATEMENT N
END FOR
Where,
<Iterator Var> is the name of variable user for the iteration. This variable is created implic-
itly.
<Coll Exprn> can be any expression which evaluates to collection name.
<Value Exprn> can be an expression and the value of this is returned in the iterator variable.
If the value expression is not specified the name of the object is returned.
<Rev Flag> can be an expression which evaluates to logical value. If it’s True then the collec-
tion objects are traversed in reverse order. This parameter is optional. The Default value is
False.
Example:
[Function : Test Function]
|
30 : FOR COLLECTION : i : Group: $ClosingBalance > 1000
40 : LOG : ##i
50 : END FOR
|
The value Yes is logged in the file ‘TDLFunc.log’ for all objects where closing balance is
greater than 1000 else No.

The looping constructs “For Collection” and “Walk Collection” are mainly
used in conjunction with Object and Context Manipulation Actions. We are cat-
egorizing them here as they are mainly used to looping purposes.

378
TDL Procedural Capabilities

FOR IN/FOR EACH– END FOR


The FOR IN loop is supported to iterate the values in the list variable. The number of iteration
depends on the number items in the list variable. This construct will walk only the elements in
the list which are having key. Since, the iterator variable is filled with a key for each element;
all elements which do not have key are ignored. This is useful to walk keyed list variable
elements in the current sorting order.
Syntax
FOR IN : < Iterator Var Name>: <List Var Name>
STATEMENT 1
|
STATEMENT N
END FOR
Where,
<Iterator Var Name> is the name of variable user for the iteration. This variable is created
implicitly.
<List Var Name> is the name of list variable.
FOR EACH is alias for the FOR IN looping construct.
Example:
FOR IN : Cnt : Test Func Var
LOG : $$String:$$ListValue:TestFuncVar:##Cnt
END FOR
All the values of the list variable 'Test Func Var' are logged in the file 'tdlfunc.txt'.

Function - $$LoopIndex
TDL Procedures give the sequential control to TDL programmers. During the sequential
execution the loops are used to iterate through a set of values. TDL allows nested loops as
well.
The function $$LoopIndex returns the count of how many times the current loop is executed.
In case of nested loops, the additional parameter <outer loop index number> can be used in the
inner loop to get the current iteration count of the outer loop.
Syntax
$$LoopIndex [: <Outer Loop Index Expr>]
Where,
<Outer Loop Index Expr> can be an expression which evaluates to number. It is optional and
the outer loop index number in the nested loop hierarchy from inner most loop to the outer
most loop. For the current loop the value is zero by default, for the parent loop One and so on.

379
TDL Procedural Capabilities

Consider following example:


[Function : LoopIndex Test]
|
05 : WALK COLLECTION : ………
|
10 : WHILE : …….
|
|
20 : FOR : ……….
30 : SET : Var: $$LoopIndex
40 : LOG : ##Var
|
80 : END FOR
100: SET : Var1: $$LoopIndex:1
|
110: END WHILE
|
|
150: END WALK

The variable Var will hold the count of how many times the FOR loop is executed while the
variable Var1 will have the count of WALK Collection loop execution.
Loops perform a set of operations repeatedly until the condition expression is satisfied or the
String/List Variable/Collection is exhausted. Sometimes, during the execution of loop at some
point it is required to skip the rest of the statements in the loop body and continue with the next
iteration or exit the loop.
Following Control Constructs are provided for the purpose
 BREAK
 CONTINUE
 START BLOCK – END BLOCK
 RETURN

380
TDL Procedural Capabilities

BREAK
When a Break statement is encountered inside the loop, the loop is immediately exited and
control is transferred to the statement immediately following the loop. When loops are nested,
the BREAK would only exit from the loop containing it. BREAK statement can be used inside
any of the looping constructs.
Syntax
BREAK
Example:
In Function ‘PrintNumbers’ loop is running from 1 to 10. But because of BREAK statement
loop will be terminated as counter reaches the 6.

[Function: PrintNumbers]
|
2: WHILE : ##Counter <= 10
3: LOG : ##Counter
4: IF : ##Counter > 5
5: BREAK
6: END IF
7: SET : Counter : ##Counter + 1
8: ENDWHILE
9: RETURN

CONTINUE
In some scenarios instead of terminating the loop, loop needs to be continued with next
iteration after skipping any statements in between. For this purpose CONTINUE statement can
be used. CONTINUE statement can be used inside any of the looping constructs.
Syntax
CONTINUE
Example:
Function to Count total number of Journal Vouchers
[Function: Count Journal]
|
02: WALK COLLECTION: Vouchers Coll
03: IF : NOT $$IsJournal:$VoucherTypeName

381
TDL Procedural Capabilities

04: CONTINUE
05: ENDIF
|
RETURN
This statement is used to return the flow of control to the calling program with or without
returning a value. When return is used the execution of the function is terminated and the
calling program continues from where it had called the function.
Syntax
RETURN : <Value Expression>
Where,
<Value Expression> is optional which returns the value to the calling environment. If the
value expression is omitted then the control is returned to the calling environment.
Example:
The Function ‘FactorialOf’ returns factorial of number
[Function: FactorialOf]
|
Returns : Number
|
70: RETURN : ##Factorial
|
START BLOCK - END BLOCK
During the execution of TDL procedure, it may be required to temporarily change the object
context for executing some intermediate actions. START BLOCK - END BLOCK are used in
this scenario. The process flow is as follows:
 START BLOCK statement saves the current object context and switches to the tar-
get context,
 All the action statements within the block are executed
 END BLOCK statement restores back the source object context.
 All the statements followed by the END BLOCK are executed with original object
context.
The object context available in the START BLOCK – END BLOCK is lost one the control
exits this block. In other words, the object context used within the block is not available
outside the block.

382
TDL Procedural Capabilities

The developer can specify the START BLOCK – END BLOCK in a nested hierarchy i.e.
START BLOCK – END BLOCK can be contained in another START BLOCK – END
BLOCK.
Syntax
START BLOCK
STATEMENT 1
|
STATEMENT N
END BLOCK

Example:
|
13 : SET : AmtVar : $$String:$Amt
14 : START BLOCK
15 : SET OBJECT
16 : SET VALUE : ActualQty : $$AsQty:##QtyVar
17 : SET VALUE : BilledQty: $$AsQty:##QtyVar
18 : SET VALUE : Amount : $$AsAmount:##AmtVar
18A: END BLOCK
19 : SET TARGET : ..
|
In the above code snippet, EDCollDetailsExtract collection is being walked over and the
values for Objects within Voucher Entry are being set.
After understanding the various programming constructs, it’s now time to understand various
actions in order to perform any operation.
9.5 Actions
As explained earlier, TDL is an action driven language, which provides a comprehensive set of
actions. All the global actions can be executed from the TDL function. Apart from these
actions, some of the actions can be executed only within the Function definition.
The functions have a comprehensive set of actions which can be used for various operations.
Classified as follows based on their usage:
 System Actions
 Object Context Manipulation
 Variable Manipulation Actions

383
TDL Procedural Capabilities

 User Interface Actions


 Debugging Actions
 File I/O Actions

9.5.1 System Actions


All the system actions are available within TDL functions for usage. The system actions are
primarily meant for the purpose of opening a report in the modes specified. The return value of
these actions is FALSE if user rejects the report, else TRUE if he accepts it.
Syntax
<Action Keyword> : <Action Parameters>
Where,
<Action Keyword> is any one of the global actions like Menu, Display, Create, etc.
<Action Parameters> parameters of the actions specified.
The return value of the actions Create, Alter and Execute is FALSE if user rejects the report,
else TRUE if he accepts it. The return value of the actions Menu and Display is TRUE if Ctrl
+ Q is used to reject the report. It returns FALSE when user uses Esc to reject the report. For
menu this is only applicable if it is the first in the stack.

Example: The Function ‘CreateReport’ opens Ledger Creation screen


[Function: CreateReport]
|
01 : Create : Ledger
|
9.5.2 Actions for Object and Context Manipulation
As explained earlier that the TDL functions can operate on two object context viz. Current
Object and Target Object context. When the TDL function is invoked the Target object context
are same as the Current Object of the caller. That means now the target object will be set to the
current object.
During the execution of function the user may require to change the object context, add a new
object, update an existing object, change value of a method etc. Here we will discuss the
various actions for manipulation of Object and Context.
SET VALUE
The value of a method for the target object can be set using the action SET VALUE. The value
formula is evaluated with respect to the current object context. The dotted method formula
syntax can be used while specifying the values. The action allows accessing any value from
the current object.

384
TDL Procedural Capabilities

Syntax
SET VALUE: <Method Name> : <Value Formula>
Where,
<Method Name> is the name of the method
<Value Formula> is the value which needs to be set to the method.
Example:
|
01: SET VALUE : Ledger Name : $LedgerName
02: SET VALUE : IsDeemedPositive : $IsDeemedPositive
03: SET VALUE : Amount : $Amount
|
The above statements set the values of Ledger Entries Object from the current Object context.

RESET VALUE
The action RESET VALUE is used to set the value of a method for Target Object using the
value formula. If value formula is not specified then it sets the existing value to null.
Syntax
RESET VALUE : <MethodName> [: <Value Formula>]
Where,
<Method Name> is the name of the method.
<Value Formula> is an optional parameter and if it is used, it will reset the value of the
method.
Example:
|
01: SET VALUE : Ledger Name : $LedgerName
02: RESET VALUE : Ledger Name : “New Value”
|
In the above code snippet RESET VALUE resets the value of the method ‘Ledger Name’ to
‘New Value’.

NEW OBJECT
The action New Object creates a new object based on the object specification and sets it as
target object. Only primary object can be specified as parameter. The actions SAVE TARGET/
ALTER TARGET/CREATE TARGET can be used along with NEW OBJECT based on the
user requirement.

385
TDL Procedural Capabilities

Syntax
NEW OBJECT : <Object Type> : [: <Object Identifier>+
[: + <Forced Create Flag>]]
Where,
<Object Type> is the type of the object to be created and
<Object Identifier> is the unique identifier of the object. If this is an existing object in Tally
data base then the further manipulations are performed on that object else it creates a new
object altogether.
<Forced Create Flag> is optional and it is required only if the <Object Identifier> is speci-
fied. If the Flag is set to TRUE then if the object identified by <Object Identifier> exists, the
object is altered otherwise a new empty object of the specified type is created.
Example:
|
01 : NEW OBJECT: Group : ##EGroupName : TRUE
02 : SET VALUE: Name : ##NGroupName
03 : SAVE TARGET
|
If the ledger identified by ##EGroupName exists in Tally database then the objects is altered
by action SAVE TARGET else a new object is created as the Forced flag is set to ‘YES’.

INSERT COLLECTION OBJECT


A new object can be inserted in the collection with the specified values using action INSERT
COLLECTION OBJECT. The action inserts the new object of the type specified in collection
and makes it as the current target object. The action accepts only secondary collection as
parameter.
Syntax
INSERT COLLECTION OBJECT : <Collection Name>
Where,
<Collection Name> is the name of the secondary collection.
Example:
|
80 : WALK COLLECTION : LedgerEntries
90 : INSERT COLLECTION OBJECT : Ledger Entries
100 : SET VALUE : Ledger Name : $LedgerName
110 : SET VALUE : IsDeemedPositive : $IsDeemedPositive

386
TDL Procedural Capabilities

120 : SET VALUE : Amount : $Amount


130 : SET TARGET : ..
140 : END WALK
150 : CREATE TARGET
|
The above code snippet inserts a new object Ledger Entries in memory under Voucher and sets
it as the target object. The action SET VALUE is used to set values of the other methods of this
target object. The action CREATE TARGET is used to save to object to Tally data base.

CREATE TARGET / ACCEPT CREATE


The action CREATE TARGET saves the target object in company data base. A new object is
created if the object does not exist in the data base otherwise it results in an error. The alias for
CREATE TARGET is ACCEPT CREATE.
Syntax
CREATE TARGET
Example:
|
80 : WALK COLLECTION : LedgerEntries
90 : INSERT COLLECTION OBJECT : Ledger Entries
100 : SET VALUE : Ledger Name : $LedgerName
110 : SET VALUE : IsDeemedPositive : +
$IsDeemedPositive
120 : SET VALUE : Amount : $Amount
130 : SET TARGET : ..
140 : END WALK
150 :CREATE TARGET
|
The above code snippet insets a new object Ledger Entries in memory under Voucher and sets
it as the target object. The action CREATE TARGET is used to save to object to Tally data
base.
SAVE TARGET / ACCEPT
The action SAVE TARGET saves the Target Object to Company Tally data base. If another
object exists in Tally data base with same identifier then the object is altered else a new object
is created. ACCEPT is an alias for action SAVE TARGET.

387
TDL Procedural Capabilities

Syntax
SAVE TARGET

ALTER TARGET / ACCEPT ALTER


The action allows altering an exiting object in the company data base. The specified object is
altered if it exists in the data base otherwise this action results in error. ACCEPT ALTER is an
alias for action ALTER TARGET.
Syntax
ALTER TARGET / ACCEPT ALTER

SET OBJECT
The action SET OBJECT sets the specified object as current object in context. If no object
specification is given the target object will be set as the current object. The action accepts only
secondary object specification.
Syntax
SET OBJECT [: <Object Spec>]
Where,
<Object Spec> is the name of the sub object.
Example:
[Function: Sample Function]
Object : Ledger : "My Test Ledger"
|
01 : LOG : $Name
02 : SET OBJECT: BillAllocations[1]
03 : LOG : $Name
04 : SET OBJECT : ..
05 : LOG : $Name
Initially the context object is Ledger so $Name give the name of Ledger. By Using ‘SET
OBJECT’ current Object is changed to first Bill allocation. Now the statement ‘03: LOG :
$Name’ logs the Bill name. The statement ‘04 : SET OBJECT : ..’ changes current object back
to Ledger using doted notation.

388
TDL Procedural Capabilities

SET TARGET
The action SET TARGET sets the specified object as target object in context. If no object
specification is given the current object will be set as the target object.
Syntax
SET TARGET: <Object Spec>
Where,
<Object Spec> is the name of the Object

Example:
01 : SET TARGET : Group
This sets the Group object as the target object in context. Later by using other methods of this
target object can be set and saved to the Tally data base.

9.5.3 Actions for Variable Manipulation


We can use the various types of Variables i.e Simple, List and Compound Variables inside
TDL/User Defined Functions for performing intermediate computations. In this chapter we
will concentrate only on those actions required for simple variable manipulation. Other actions
available for List and Compound Variables will be taken up in the chapter on “Variable Frame-
work”
SET
The action SET is used to assign a value for a variable. It accepts variable name and its value
as parameters.
Syntax
SET : <Variable Name> : <Value Expression>
Where,
<Variable Name> is the variable for which value needs to be assigned.
<Value Expression> is the formula evaluating to value.
Example:
[Function: FactorialOf]
|
Variable : Factorial : Number
|
2: SET : Factorial : 1
|

389
TDL Procedural Capabilities

EXCHANGE
During the execution of a TDL procedure, there may be a requirement to swap the values of
two variables. This can be performed for variables of same data type only. The action
EXCHANGE is used to interchange the value of two variables.
Syntax
EXCHANGE: <FirstVariableName> : <Second Variable Name>
Where,
<First Variable Name> and <Second Variable Name> are the Variables whose values needs
to be swapped.
Example:
|
01: EXCHANGE : Var1 : Var2
|
In the above statement both variables are of type Number and their values are swapped.

INCREMENT
This Action is used to increment the value of a Variable by specified number. INCREMENT
can be used inside the loop to increment value of the control variable.
Syntax
INCREMENT : <Variable Name> [ : < Increment Counter>]
Where,
<Variable Name> is the name of the Simple Non Repeat Variable of Number type whose
value needs to be incremented.
<Increment Counter> is an optional parameter which specifies the increment count. If this is
not specified then the variable by default is incremented by 1.
Example:
[Function: FactorialOf]
|
5: INCREMENT : Counter
6: INCREMENT : Factorial : 5
|
The value of the variable ‘Counter’ is incremented by 1 whereas the value of the variable
‘Factorial’ is incremented by 5. Assuming the initial value of both the variables is 1 then after
the execution of the statements the values will be 2 and 6 respectively.

390
TDL Procedural Capabilities

DECREMENT
The action DECREMENT is used to decrement the value of a Variable by specified number.
Syntax
DECREMENT : <Variable Name> [ : < Increment Counter>]
Where,
<Variable Name> is the name the Simple Non Repeat Variable of Number type whose value
needs to be decremented.
<Increment Counter> is an optional parameter which specifies the decrement count. If this
is not specified then the variable is decrement by 1.
Example:
[Function: FactorialOf]
|
5: DECREMENT : Counter
6: INCREMENT : Factorial : 5
|
The value of the variable ‘Counter’ is decremented by 1 whereas the value of the variable
‘Factorial’ is decremented by 5. Assuming the initial value of both the variables is 10 then
after the execution of the statements the values will be 9 and 5 respectively.

9.5.4 User Interface Actions


Sometimes a Function may take some time to complete the task. It is always better to indicate
the user that the task is occurring, how long the task might take and how much work has
already been done. One way of indicating the amount of progress, is to use an animated image.
This can be achieved by using following Actions.
 START PROGRESS
 SHOW PROGRESS
 END PROGRESS

START PROGRESS
The action START PROGRESS is used to display the Progress Bar. The details like total
number of steps involved in the task, Title, Sub Title and Subject of the Progress Bar can be
displayed along with the progress bar.
Syntax
START PROGRESS : <Number of steps> :< Title> +
[:< Sub Title> :< Subject>]

391
TDL Procedural Capabilities

Where,
<Number of steps> denotes the whole task quantified as a number,
<Title>, <Sub Title> and <Subject> shows the Title, Sub Title and Subject of Progress Bar
respectively.
Example:
START PROGRESS: ##TotalSteps:“TDS Migration”:@@CmpMailName: +
“MigratingVouchers..”

SHOW PROGRESS
The action SHOW PROGRESS shows the current status of the task to the user.
Syntax
SHOW PROGRESS : <Number of Steps Completed>
Where,
<Number of Steps Completed> is a number denotes the amount of work completed
Example:Progress Bar showing the progress of the task
SHOW PROGRESS:##Counter
END PROGRESS
When a task is completed, Progress Bar can be stopped by using action END PROGRESS.
This Action does not take any parameter.
Syntax
END PROGRESS
In any programming language dialog boxes are used to display some information or to get
confirmation from the application user. TDL provides actions MSG BOX and QUERY BOX
to display dialog boxes. The parameters that are passed to these actions decide the behaviour
of the dialog box.

MSG BOX
The action MSG BOX is used to display a message box to user. It comes back to the original
screen on the press of a key. This is can be used by the programmers to display intermediate
values of variables during calculations thus helping in error diagnosis.
Syntax
MSG BOX : <Title Expression> : <Message Expression> : +
<Grey Back Flag>

392
TDL Procedural Capabilities

Where,
<Title Expression> is the value displayed on the title bar of the message window
<Message Expression> is the actual message which is displayed in the box. This can be an
expression as well i.e., the variable values can be concatenated and displayed along with the
message in the display area of the box
<Grey Back Flag> accepts logical value YES or NO. If the value is YES, the message box is
displayed with Grey background color.
Example:
01: MSGBOX: “Return Value” : ##Factorial
|
The above code snippet displayed the value of the variable ‘Factorial’ in the dialog box and
the string ‘Return Value’ is displayed as title of the box.

QUERY BOX
The action displays a confirmation box and waits for the user response. The user input in the
form of YES or NO is required.
Syntax
QUERY BOX : <Message Expression> : <Grey Back Flag> +
: <Esc As Yes>
Where,
<Message Expression> is the message which is displayed inside the box. This can be an
expression
<Grey Back Flag> accepts logical value YES or NO. If the value is YES, the message box is
displayed with Grey background color.
<Escape as Yes> is a flag which indicates the response when the user presses ESC key. This
can be specified as YES/NO. A YES value for this flag indicates that the response should be
treated as YES on press of an ESC key.
9.5.5 Debugging Actions
In scenarios, when the actual program output differs from the expected behaviour, the applica-
tion programmer needs to check the code and fix the problem. This process of locating and
correcting the errors in the code is referred as Debugging. While debugging a program the user
requires displaying the intermediate values in order to isolate the source of the problem.
Example:
The intermediate values of the expression can be displayed during expression evaluation. TDL
supports various actions to help the programmer in debugging. The actions allows to display
value in the Calculator window and also writes them to the log file ‘tdlfunc.log’ available in
the application directory. By default logging is enabled inside the function.

393
TDL Procedural Capabilities

LOG
The action LOG displays the value passed as parameter in the calculator window and writes
the same in the log file ‘tdlfunc.log’. This is very much helpful for debugging the expression
Syntax
LOG : < Expression>
Where,
<Expression> is an expression whose value needs to be passed to the calculator window.
Example: While calculating the factorial of a number, intermediated values are displayed in
the Calculator window using LOG action

[Function: FactorialOf]
|
3 : WHILE : ##Counter <= ##InputNumber
4 : SET : Factorial : ##Factorial * ##Counter
5 : SET : Counter : ##Counter + 1
5a: LOG : ##Factorial
|
The value of the variable ‘Factorial’ is displayed in the calculator window and is also logged
in the file ‘tdlfunc.log’.

SET LOG ON
While debugging a TDL function, sometimes it is required to conditionally Log the values of
an expression. If logging is stopped, then logging can be re-started based on the condition
Action SET LOG ON. This Action does not require any parameter.
Syntax
SET LOG ON
Syntax
[Function : Debugtest]
00 a : SET LOG ON
00 b : Log : "Tally"

The string “Tally” is displayed in the calculator window as well as it is logged in the file ‘tdl-
func.log’.

394
TDL Procedural Capabilities

SET LOG OFF


When the logging on the Calculator window is not desirable, it can be stopped using action
SET LOG OFF. The value specified by LOG is not displayed in the Calculator window but it
is logged in the ‘tdlfunc.log’. This action can be used in conjunction with SET LOG ON.
Syntax
SET LOG OFF
Example:
[Function : Debugtest]
00 c : SET LOG OFF
00 d : Log : "Solutions"
The string Solutions is not displayed in the calculator window but it is logged in the file ‘tdl-
func.log’.

SET FILE LOG ON


The action SET FILE LOG ON is used to log the values of an expression specified by action
LOG in the log file ‘tdlfunc.log’.
Syntax
SET FILE LOG ON
Example:
[Function : Debugtest]
00 e : SET FILE LOG ON
00 f : LOG : "Private"
The string Private is displayed in the calculator window as well as it is logged in the file ‘tdl-
func.log’.

SET FILE LOG OFF


When the logging of the values in the file ‘tdlfunc.log’ is not desirable, it can be stopped using
action SET FILE LOG OFF. The value specified by LOG is not is logged in file the ‘tdl-
func.log’ but it is displayed in the Calculator window.
Syntax
SET FILE LOG OFF
Example:
[Function : Debugtest]
00 g : SET FILE LOG OFF
00 f : Log : "Ltd."

395
TDL Procedural Capabilities

The string “Ltd.” is displayed in the calculator window but it is not logged in the file ‘tdl-
func.log’.

LOG OBJECT
The action Log Object a global action which allows logging the current object context details
in a file. It accepts filename as a parameter. In the specified file the current context object, cor-
responding methods and sub collections are logged.
Syntax
LOG OBJECT [:<path\filename>[:<Overwrite Flag>]]
Where,
<path/filename> is optional. It accepts the name of file along with the path in which the log is
created. If no file name is specified the contents of object are logged in "TDLfunc.log" when
logging is disabled otherwise it logs in to the Calculator window.
<Overwrite Flag> is used to specify whether the contents should be appended or overwritten.
The default is No, which appends the content in the file. If YES, then the file is overwritten.
Example:
[Function: FuncLedExp]
|
Object : Ledger
|
10: Log Object : LedgerObj.txt
In the file ‘LedgerObj.txt’ the current object context, its methods and collection details are
logged.

LOG TARGET
The action Log Target is function specific action which allows logging details of the target
object in a file. It accepts filename as a parameter in which the log of object, its method and
collection is created for the target object.
Syntax
Log Target[:<path\filename>[:<Overwrite Flag>]]
Where,
<path/filename> is optional. It accepts the name of file along with the path in which the log is
created. If no file name is specified the contents of object are logged in "TDLfunc.log" when
logging is disabled otherwise it logs in to the Calculator window.
<Overwrite Flag> is used to specify whether the contents should be appended or overwritten.
The default is No, which appends the content in the file. If YES, then the file is overwritten.

396
TDL Procedural Capabilities

Example:
[Function: FuncLedExp]
|
05: Set Target
|
10: Log Target : LedgerTgtObj.txt
In the file ‘LedgerTgtObj.txt’ the target object context, its methods and collection details are
logged.

Exercise 9.2:
Objective
The objective of this program is to create Groups and Ledgers by executing the action 'New
Object' within the Function definition.
Capabilities Used
 The TDL Procedural programming constructs Variable, Local Formula, MSG Box,
While Loop etc are used.
 The actions New Object, SET Value, Save Target are used to create the objects.
Code
[Function: Exer Action New Object]
Variable : Counter: Number: 5
Local Formula: LFRM: "Debtor " + ($$String:##Counter)
Local Formula: OpBal: ($$AsQty:##Counter)
Local Formula: CX1000: (##Counter * 1000)
;; Ensuring that the Group is available, if not creating the same
000: NEW OBJECT : Group: "Bangalore Debtors": Yes
;; Action 'SET VALUE' is used to set the value of a Method within the current Object
010: SET VALUE : Name : "Bangalore Debtors"
020: SET VALUE : Parent : "Sundry Debtors"
;; Action 'SAVE TARGET' is used to save the Target Object.
030: SAVE TARGET
040: MSGBOX : "Success" : "Group created/altered successfully"
050: WHILE: ##Counter > 0
;; Creating 5 Ledgers under the Group 'Bangalore Debtors'

397
TDL Procedural Capabilities

060: NEW OBJECT: Ledger : @LFRM: Yes


070: SET VALUE : Name : @LFRM
080: SET VALUE : Parent : "Bangalore Debtors"
;; Setting the Target Object as the current Context Object
090:SET OBJECT
/* If No Bill Allocations are found, then inserting an Object else Setting first object of Bill Allocations are target object*/
100:IF : $$NumItems:BillAllocations = 0
110: INSERT COLLECTION OBJECT: Bill Allocations
120:ELSE:
130: SET TARGET: Bill Allocations[1]
140:ENDIF
150:SET VALUE: Name : ($$String:##Counter)
160:SET VALUE: BillDate : ($$Date:"31-3-2011")
170:SET VALUE: OpeningBalance: (-1 * $$AsAmount:@CX1000)
/* Moving the target context back to its parent context i.e., moving from Bill Allocations to Ledger*/
180:SET TARGET: ..
190:SET VALUE: OpeningBalance : (-1 * $$AsAmount:@CX1000)
200:SAVE TARGET
210:DECREMENT: Counter
220:END WHILE
230: MSGBOX: "Success" : "Ledgers created/altered successfully"
;; End-of-File

Output

398
TDL Procedural Capabilities

Program Explanation
The function Exer Action New Object creates the Group Object Bangalore Debtors using
the action NEW OBJECT. The Group Bangalore Debtors is created only if it does not exist
else it alters the same. The action SET VALUE sets the values of the methods Name and
Parent as Bangalore Debtors and Sundry Debtors. The action SAVE TARGET is used to
save the newly created Group in Tally Database.
Once the Group is created the success message is displayed using action MSG BOX as shown
in the image.
When the user escapes from the message box then the Ledgers are created. Since the value of
the variable Counter is set to 5; five Ledgers Debtor 1, Debtor 2, Debtor 3, Debtor 4 and
Debtor 5 are created. If a ledger with the same name already exists then the ledger is altered.
The action SET OBJECT is specified to set the ledger object as the current object in context
for entering the Bill details. The action INSERT COLLECTION is then used to enter the Bill
allocation details for the current ledger. The Action SET TARGET is used to move the context
from Bill Allocations to Ledger object.
On successful creation of Ledgers and their respective bill allocations, the success message is
displayed as shown in the second image.

9.5.6 File Input/Output Actions


Note :The various File I/O actions will be discussed along with the detailed discussion on File
Input/Output Capability as a whole in the subsequent section on ”File Input/Output Capabil-
ity”
Dynamic Actions inside TDL/User Defined Functions
As we already know Dynamic Action capability allows the programmer to execute actions
based on dynamic evaluation of parameters. The Action keyword can as well be evaluated

399
TDL Procedural Capabilities

dynamically. Dynamic actions are supported within TDL functions also as per the syntax
given below
Syntax
ACTION : <Action Keyword Expression>: <Action Parameter Expres-
sion>

Where,
<Action Keyword Expression> is an expression evaluating to an Action Keyword i.e. any of
the global action name like Display, Print, Upload etc.
<Action Parameter Expression> is an expression evaluating to Action Parameters
Example:
[Button: Test Button]
Key : F6
Action : Call : TestFunc :"Balance Sheet"

[Function: Test Func]


Parameter : Test Func : String
01 : ACTION : Display : ##TestFunc
The function TestFunc dynamically executes action DISPLAY which takes the report name as
the parameter passed to it.

9.5.7 File Input/Output Capability


As we are aware, any high level programming language supports Reading and Writing From/
To multiple hardware devices. It will have predefined constructs in form of functions to Read
and Write from a File as well. This file can reside on the hard disk or a network which can be
accessed via various protocols HTTP or FTP.
This capability introduced in TDL now will pave the way for supporting import/export opera-
tions from the Tally data base in the most amazing way. It will now be possible to export
almost every piece of information in any Data Format which we can think of. We support Text
and Excel Format which allow data storage in SDF-Fixed Width ,CSV-comma separated etc
sufficing the generic data analysis requirements of any business.
The TDL Artifacts used for supporting various Read/Write operations are Actions and Func-
tions. These are made to work only inside the TDL Procedural Block. Write operations are
mostly handled using Actions and all file Access and Read operations are performed using
Functions. These give tremendous control in the hands of the programmer for performing the
data manipulations To/From the file. And that too on a file present on a network is accessible

400
TDL Procedural Capabilities

using the protocols FTP and HTTP. Since these artifacts operate on characters and not bytes
the file encoding ASCII/UNICODE does not have any effect on the operations.
The entire procedural Read/Write artifacts basically operate on two file contexts.

Source File Context


When a file is opened for Reading purpose, the context available for all read operations is the
Source File Context. All the subsequent read operations a performed on the Source File
Context.

Target File Context


When a file is opened for writing purpose, the context available for all write operations is the
Target File Context. All the subsequent Write operations are performed on the Target File
Context.
It is important to understand that these contexts are available only inside the procedural block
where the files are opened for use. The file context concept is different from the concept of
object context where the object context is carried over to all its child objects. File Contexts are
only available to the functions and subsequent functions called from within the parent
Function. The called function can override the inherited context by opening a new file within
its block.
The file contexts created by opening a file is available only till the execution of the last state-
ment. Once the control is out of the function the file is automatically closed. However, it is
highly recommended as a good programming practice to close a file on exit.
Both the file contexts i.e. Source and Target file are available simultaneously. This makes it
possible to read from one file and write to another file simultaneously.

File Operations
A programming language which supports File Read/Write typically support following funda-
mental operations:
 Open – This is an operation which identifies the file which needs to be opened for
Read/Write purpose
 Close - This is an operation which closes the opened file after Read/Write
 Read – This is an operation to read the data from an opened File
 Write – This is an operation to write the data to an opened File
 Seek - This is an operation to the character position in an already opened file
 Truncate- This is an operation which will delete the particular no of characters/entire
contents of the file

401
TDL Procedural Capabilities

The TDL Artifacts used for supporting various Read/Write operations are Actions and Func-
tions. These are made to work only inside the TDL Procedural Block. Write operations are
handled using Actions and all file Access and Read operations are performed using Functions.

Generic File Operations


As discussed above the entire procedural Read/Write concepts basically operate on two file
contexts. A source file context and a target file context. Source context is used to read the
contents from a file which is opened for reading purpose, where as the target context is used to
write the data to a file which is opened for writing purpose. Since both these file contexts are
available simultaneously it is possible to read from one file and write to another file.

OPEN FILE
This action OPEN FILE is used to open a Text/Excel file for read/write operations. The File
can reside in Hard Disk, can be in main memory or can be in FTP/HTTP site. Also this Action
is used to open a file for read/write operations.
If no parameters are used then a memory buffer will be created and will act as a file. This file
will be in both read / write mode and will act as both source as well as target context.
Based on the mode specified (read / write) the file automatically becomes the source file or
target file respectively.
Syntax
OPEN FILE [: <File Name> [: <File Format> [: <Open Mode> +
[: <Encoding>]]]]
Where,
<File Name> can be a expression which evaluates to a regular disk file name like “C:\Out-
put.txt” or to a HTTP/FTP site like “ftp://ftp.tallysolutions.com/Output.txt”
<File Format> can be either Text or Excel. By default text mode will be considered if not
specified. Also during opening an existing file, if the mode does not match the Action will fail.
<Open Mode> can be read / write. By default it is read. If a file is opened for read purpose
then it must exist. If write mode is specified, and the file exists this will be open it for updating
or if file does not exist a new file is created. If the file is opened in the Write mode, it is also
possible to read from the file as well.
<Encoding> can be ASCII or Unicode. If not specified it will consider Unicode as default
value for Write Mode. In read mode this parameter will ignored and considered based on the
encoding of the file being read.
If the specified file does not exist and the mode is specified as Write then the action OPEN
FILE creates the file otherwise the file is opened in the specified mode.

402
TDL Procedural Capabilities

If the specified file does not exist and the mode is specified as Read then the action OPEN
FILE will fail.
Incase only the file name is specified then the default path is considered as the Tally.ERP9
application folder to open/create the file.
Example:1
|
10 : OPEN FILE : "Output.txt" : Text : Write : ASCII
|
The action opens a Text file ‘Output.txt’ in Write mode from the Tally.ERP9 application
Folder. If the file does not exist then the file with the given name is created in the Tally.ERP9
application Folder. In case the file already contains some text then the same file will be opened
for appending purpose.
Example:2
|
10: OPEN FILE : "http://www.tallysolutions.com/Output.txt" : Text
|
The action opens a Text File ‘Output.txt’ in Write mode at the HTTP URL specified. If the file
already exists the same file will be opened for appending purpose. (If the file does not exist
then it is created on the site if the user has Right to create the file)
Example:3
|
10 : OPEN FILE : "C:\Output.xls" : Excel : Read
|

The action opens a Excel File ‘Output.xls’ in Read mode under C drive and if the file does not
exist the action will fail.

Please refer to the functions like $$MakeFTPName and $$MakeHTTPName for


constructing the FTP and HTTP URLs using the various parameters like server
name, user name, password etc. Refer to Tally.Developer 9 Function Browser
for help on usage.
A file which is opened for Read/Write operation needs to be closed once all the read/write
operations are completed. However if the files are not closed explicitly by the programmer,
these are closed by default when the function is returned. But it is always recommended to
close the file after the operations are completed.

403
TDL Procedural Capabilities

Files which are opened in the current function can only be closed by it. If a function inherits
file contexts from the caller function then it cannot close these files, however it can open its
own instances of the files, in such cases the caller context files will not be accessible.

CLOSE FILE
The action CLOSE FILE is used to close a opened source file.
Syntax
CLOSE FILE
Example:
|
10 : OPEN FILE : "Output.xls" : Excel : Read
|
30 : CLOSE FILE
|
In the example Excel file ‘Output.xls’ which is opened for reading purpose is closed.

CLOSE TARGET FILE


The action CLOSE TARGET FILE is used to close an opened target file.
Syntax
CLOSE TARGET FILE
Example:
|
10: OPEN FILE : "Output.txt" : Text : Write
|
30: CLOSE TARGET FILE
|
In example the text file ‘Output.txt’ which is opened for writing purpose is closed.
Generic Functions
TDL provides functions to change the current file context, to get the file size etc. These
functions can be used by the application developer while performing the read/write operation
on a file.

404
TDL Procedural Capabilities

$$TgtFile
All file accessing functions for both text and excel files, operates on the source file context.
The function $$TgtFile can be used to switch to target file context temporarily. This function
which evaluates the expression passed in the context of a target file.
Syntax
$$TgtFile:<Expression>
Where
<Expression> is any expression which is evaluated the context of a target file.
Example:
In the example below, the objective is to Read the content of a cell in Sheet 1 and copy it to a
cell in the Sheet 2 of the same file. The function opens the file “ABC.xls” in Write mode.
[Function: Sample Func]
|
Variable : Temp : String
|
10 : SET : Temp : ""
20 : OPEN FILE : "Output.xls" : Excel : Write
|
30 : ADD SHEET : "Sheet 1"
40 : WRITE CELL : 1 : 1 : "Item A"
50 : SET : Temp : $$TgtFile:$$FileReadCell:1:1
60 : ADD SHEET : "Sheet 2"
|
70 : WRITE CELL : 1:1: ##Temp
80 : CLOSE TARGET FILE
In this example there is no file present in the source file context as the file is opened in the
Write mode. In that case, for reading a value from Sheet 1, the expression $$FileReadCell:1:1
will return no value. Prefixing the expression with $$Tgtfile will temporarily change the
context to Target File for the evaluation of expression and will fetch the value from cell 1 of
Sheet 1 existing in the Target File context.
$$FileSize
This function will return the size of the file specified in bytes. This function takes optional
parameter if the parameter is not given then it works on the current context file and returns the
size.

405
TDL Procedural Capabilities

Syntax
$$FileSize[:<FileName>]
Where
<FileName> is an expression which evaluates to the file name along with the path.
Example:
|
10 : Log : $$FileSize:”Output.xls”
|
The example gives the size of Excel file ‘Output.xls’ in terms of bytes.

9.5.8 Read/Write Operation on Text Files


Writing to a File
Various Actions are introduced in order to write to a text file. These Actions operate on the
Target File context. The scope of these Actions is within the TDL procedural block(User
Defined Functions) where the file is opened and the context is available.

WRITE FILE
This Action is used to append a file with the text specified. The write always starts from the
end of the file. This action always works on the target file context.
Syntax
WRITE FILE : <TextToWrite>
Where,
<TextToWrite> can be any expression which evaluates to data that need to be written to the
file.
Example:
|
10 : OPEN FILE : "Output.txt" : Text : Write
20 : WRITE FILE : "Krishna"
30 : CLOSE TARGET FILE
|
In the example a txt file ‘Output.txt’ is opened in write mode and the content ‘Krishna’ is
appended at the end of the file.

406
TDL Procedural Capabilities

WRITE FILE LINE


This Action is similar to WRITE FILE but it also places a new line character (New Line/
Carriage Return) after the text. All the subsequent writes begin from the next line. This action
always works on the target context.
Syntax
WRITE FILE LINE: <TextToWrite>
Where,
<TextToWrite> can be any expression which evaluates to data that need to be written to the
file.
Example:
|
10 : OPEN FILE : "Output.txt" : Text : Write
20 : WRITE FILE LINE: "Line 1"
30 : WRITE FILE LINE: "Line 2"
40 : CLOSE TARGET FILE
|
In the example a txt file ‘Output.txt’ is opened in write mode and the two more lines were
appended to the end of the file.

TRUNCATE FILE
This action removes the content of the file by setting the file pointer to the beginning of the file
and inserting an end of file marker. This can be used to erase all characters from an existing
file before writing any new content to it.
Syntax
TRUNCATE FILE
Example:
|
10 : OPEN FILE: "Output.txt" : Text : Write
20 : TRUNCATE FILE
30 : WRITE FILE : "New Value"
40 : CLOSE TARGET FILE
|
The entire content of the existing txt file ‘Output.txt’ is removed and ‘New Value’ is inserted
subsequently.

407
TDL Procedural Capabilities

SEEK FILE
This Action operates on the Target File Context. This Action is used to move the file pointer to
a location as specified by the no of characters. As we know that it is possible to Read and
Write from the Target File context, all the subsequent Reads and Writes will be starting from
this position. By Default, if the file position is not specified Read pointer will be always be
from the beginning of file and write pointer will be from the end of the file.

We have already covered how to Read from Target File Context by using the
function $$TgtFile

Syntax
SEEK FILE:<File Position>
Where,
<File Position> can be any expression which evaluates to number which considered as
number of characters.

9.5.9 Reading a File


Some functions and Actions are introduced which can operate on the Source File context to
read from the file or access some information from them. The scope of these functions is
within the TDL procedural block(User Defined Functions) where the file is opened and the
context is available. It is also possible to read from the Target File Context by using the
function $$TgtFile.

$$FileRead
This function is used to read data from a text file. This takes an optional parameter. If this is
not specified or parameter is having value as 0 then this will read one line and ignore the end
of line character. However the file pointer is positioned after the end of line character so that
next read operation starts on the next line.
If number of characters are mentioned this function will read that many number of characters.
Syntax
$$FileRead [:<CharsToRead>]
Where,
<CharsToRead> can be any expression which evaluates to number of characters to read.

408
TDL Procedural Capabilities

Example:
|
10 : OPEN FILE : “Output.txt" : Text : Read
|
20 : LOG : $$FileRead
30 : CLOSE FILE
|
The example reads the first line of the text file ‘Output.txt’.

$$FileIsEOF
This function is used to check if the current character being read is the End of file character.
Syntax
$$FileIsEOF

SEEK SOURCE FILE


This Action works on a source file context. This action sets the current file pointer to the
position specified. Zero indicates the beginning of the file and -1 indicates the end of the file.
The file position is determined in terms of the characters. All the subsequent reads begin from
this position onwards.
Syntax
SEEK SOURCE FILE: File Position
Where,
<File Position> can be any expression which evaluates to number which is number of charac-
ters.
Example:
In the example below the first line of the file ‘Output.txt’ is read starting from the 3 character.
10 : OPEN FILE : "Output.txt" : Text : Read
20 : SEEK SOURCE FILE : 2
30 : LOG : $$FileRead
40 : CLOSE FILE
9.5.10 Read/Write Operation on Excel Files
For an Excel file all Read and Write operations will be performed on an Active Sheet.
SET ACTIVE SHEET
This Action is used to change the Active Sheet during read and write operations.

409
TDL Procedural Capabilities

Syntax
SET ACTIVE SHEET: <Sheet Name>
Where,
<Sheet Name> can be an expression which evaluates to the string and will be considered as
the name of the sheet.
Example:
|
10 : OPEN FILE: "Output.xls" : Excel : Read
20 : SET ACTIVE SHEET :"Sheet 2"
30 : Log : $$FileReadCell:1:1
40 : CLOSE FILE
|
The example opens an Excel sheet ‘Output.xls’ in Read mode and makes ‘Sheet 2’ as active
and reads the content from the first cell.
9.5.11 Writing to a File
Various Actions are introduced in order to write to a excel file. These Actions operate on the
Target File context. The scope of these Actions is within the TDL procedural block (User
Defined Functions) where the file is opened and the context is available.

ADD SHEET
This Action adds a sheet in the current workbook which is opened for writing. Sheet will
always be inserted at the end .If a sheet with the same name already exists the sheet will be
made as active.
Syntax
ADD SHEET : <Sheet Name>
Where,
<Sheet Name> can be an expression which evaluates to the string and will be considered as
the name of the sheet.
Example:
|
10 : OPEN FILE : "Output.xls" : Excel : Write
20 : ADD SHEET : "New Sheet"
|

410
TDL Procedural Capabilities

The example opens an existing Excel sheet ‘Output.xls’ in write mode and new sheet ‘New
Sheet’ will be inserted at the end of the workbook.

REMOVE SHEET
This Action removes the specified sheet from current workbook. The entire content in the
sheet will be removed. This Action will fail if the workbook has only one sheet or if the
specified sheet name does not exist in the workbook.
Syntax
REMOVE SHEET : <Sheet Name>
Where,
<Sheet Name> can be an expression which evaluates to the string and will be considered as
the name of the sheet.
Example:
|
10 : OPEN FILE : “Output.xls” : Excel : Write
20 : ADD SHEET : "New Sheet"
30 : REMOVE SHEET : "Sheet1"
|
The example creates a work book with a sheet ‘New Sheet’.

RENAME SHEET
The Excel work sheet can be renamed using the action RENAME SHEET.
Syntax
RENAME SHEET: <Old Sheet Name>: <New Sheet Name>
Where,
<Old Sheet Name> and <New Sheet Name> can be an expression which evaluates to the
string and will be considered as the name of the sheet.
Example:
01: OPEN FILE: "Output.xls" : Excel : Write
02: RENAME SHEET : @@OldSheetName : @@NewSheetName
03: CLOSE TARGET FILE
The sample code renames the worksheet identified by expression ‘OldSheetName’ to the
string identified expression ‘NewSheetName’.

411
TDL Procedural Capabilities

WRITE CELL
This action allows to write the specified content at the cell address specified by row and
column number of the currently active sheet.
Syntax
WRITE CELL: <Row Number> : <Column Number> : +
<Content To be Written>
Where,
<Row Number> and <Column Number> can be any expression which evaluates the number
which can be used to identify the cell
<Content To be Written> can be any expression which evaluates to data which needs to be
filled for the identified cell.
Example:
|
10 : OPEN FILE : "Output.xls" : Excel : Read : ASCII
15 : ADD SHEET : "New Sheet"
20 : WRITE CELL : 1 : 1 : "Krishana"
30 : CLOSE FILE
|
The example opens an Excel file ‘Output.xls’, adds a new sheet and in that sheet first cell will
have content as ‘Krishna’.

WRITE ROW
This Action writes multiple cell values at a specified row in the Active sheet. The numbers of
values separated by commas are written starting from the initial column number specified for
the row specified.
Syntax
WRITE ROW: <Row Number> : <Initial Column Number>: +
<Comma Separated Values>
Where,
<Row Number> and <Initial Column Number> can be any expression which evaluates the
number which can be used to identify the cell
<Comma Separated Values> can be expressions separated with comma which evaluates to
data that needs to be filled starting from cell as mentioned by <Row Number> and <Initial
Column Number>.

412
TDL Procedural Capabilities

Example:
|
10 : OPEN FILE : "Output.xls" : Excel : Write
20 : ADD SHEET : "New Sheet"
30 : WRITE ROW : 1 : 1 : @@Val1, @@Val2
40 : CLOSE TARGET FILE
|
The examples fills cell (1,A) and cell (1,B) with the values from expressions ‘Val1’ and ‘Val2’

WRITE COLUMN
This action writes multiple cell values at a specified column in the Active sheet. The no of
values separated by commas are written starting from the initial row no specified for the
column.
Syntax
WRITE COLUMN: <Initial Row Number>: <Column Number> : +
<Comma Separated Values>
Where,
<Initial Row Number> and <Column Number> can be any expression which evaluates the
number which can be used to identify the cell.
<Comma Separated Values> can be expressions separated with comma which evaluates to
data that needs to be filled starting from cell as mentioned by <Initial Row Number> and
<Column Number>.
Example:
|
10 : OPEN FILE: "Output.xls" : Excel : Write
20 : ADD SHEET : "New Sheet"
30 : WRITE Column : 5 : 5 : @@Val3, @@Va4
40 : CLOSE TARGET FILE
|
The example sets the values from expressions ‘Val3’ and ‘Val4’ in the cell (5,E) and cell (6,E)
respectively.
9.5.12 Reading a File
Some functions and actions are introduced which can operate on the Source File context to
read from the file or access some information from them. The scope of these functions is

413
TDL Procedural Capabilities

within the TDL procedural block (User Defined Functions) where the file is opened and the
context is available. It is also possible to read from the Target File Context by using the
function $$TgtFile.

$$FileReadCell
To read the content of a specific cell function $$FileReadCell can be used. This function
returns the content of the cell identified by using row and column number of the active sheet.
Syntax
$$FileReadCell : <Row Number> : <Column Number>
Where,
<Row Number> and <Column Number> can be expression which evaluates to the number
to identify row number and column number
Example:
|
10 : OPEN FILE: "Output.xls" : Excel : Read
20 : SET ACTIVE SHEET :"Sheet 1"
20 : Log : $$FileReadCell:1:1
|
The function $$FileReadCell Logs the contents of the first cell of the excel sheet ‘Sheet 1”.

$$FileGetSheetCount
Before performing any operation on the Excel file the user may require to know the number of
sheets in the Excel work book. The function $$FileGetSheetCount can be used which returns
number of sheets in the current workbook.
Syntax
$$FileGetSheetCount
Example:
|
10: OPEN FILE: "Output.xls" : Excel : Read
20: Log : $$FileGetSheetCount
|
The function $$FileGetSheetCount returns the total number of sheets in an Excel sheet ‘Out-
put.xls’

414
TDL Procedural Capabilities

$$ FileGetActiveSheetName
The developer might need to know the name of the active work sheet before performing in
operation on the Excel file. The function $$FileGetActiveSheetName can be used which
returns the name of the active sheet.
Syntax
$$FileGetActiveSheetName

Example:
|
10 : OPEN FILE: "Output.xls" : Excel : Read
20 : Log : $$FileGetActiveSheetName
|
The function $$FileGetActiveSheetName returns the name of the active sheet after opening
the Excel file ‘Output.xls’

$$ FileGetSheetName
If the work sheet index is available then the function $$FileGetSheetName can be used to
retrieve the name of the sheet. This Function returns the name of the sheet at a specified index.
Syntax
$$GetSheetName:< Sheet Index>
Where,
<Sheet Index > can be any expression which evaluates to number as Sheet Index.

Example:
|
10 : OPEN FILE: "Output.xls" : Excel : Read
|
20 : Log :$$FileGetSheetName:1
|
The function $$FileGetSheetName gives the name of the sheet available at index 1.

$$ FileGetSheetIdx
If the work sheet name is available then the function $$FileGetSheetIdx can be used to get the
index of the sheet. This function returns the Index of the specified sheet name.

415
TDL Procedural Capabilities

Syntax
$$FileGetSheetIdx:<Sheet Name>
Where,
<Sheet Name> can be any expression which evaluates to the name of the Excel work sheet.
Example:
|
10: OPEN FILE: "Output.xls" : Excel : Read
20: Log :$$FileGetSheetIdx:"Ledgers"
|
The function $$FileGetSheetIdx gives the index number of the work sheet ‘Ledgers’.

$$FileGetColumnName
If the column index is available then the function $$FileGetColumnName can be used to get
the column name. This function gives column name as alphabets for given index from the
current excel work sheet.
Syntax
$$FileGetColumnName:<Index>
Where.
<Index> can be any expression which evaluates to the Index number.
Example:
|
10 : OPEN FILE: "Output.xls" : Excel : Read
20 : Log : $$FileGetColumnName:10
|
The function $$FileGetColumnName returns value J for the specified index 10.

$$FileGetColumnIdx
If the column name is available then the function $$FileGetColumnIdx can be used to get
the column index. This function returns the index of the column for a given alphabetical name.
Syntax
$$FileGetColumnIdx:<Name>
Where,
<Name> can be any expression which evaluates to name of the column in alphabets.

416
TDL Procedural Capabilities

Example:
|
10: OPEN FILE: "Output.xls" : Excel : Read
|
20: Log :$$FileGetColumnIdx:AA
|
The function $$FileGetColumnIdx returns the column index value for the column ‘AA’ i.e.
27.
Exercise 9.3:
Objective
The objective of this program is to read from a text file which has the following format and
write to an Excel file:
Capabilities Used
 The TDL Procedural programming constructs Variable, Local Formula, MSG Box,
While Loop etc. and various File IO Operations are used.
 The actions New Object, SET Value, Save Target are used to create the objects.
Code
[Function: Exer RFT and WTE]
;; Read from Text and Write to Excel
Variable : Text Line: String
Variable : RowCounter : Number : 3
Variable : ColCounter : Number
/* 2 files are opened one for reading and other for writing i.e., one is the source (Text) other is the target (Excel) File
"TextFile.txt" of Type Text written earlier is opened in Read Mode*/
00: OPEN FILE : "TextFile.txt": Text : Read
;; File "WriteFile.xls" of Type Excel is opened in Write Mode
10: OPEN FILE : "WriteFile.xls": Excel: Write
20: ADD SHEET: "From Text File"
/*All the reading operations are performed on the source file i.e., FileRead Function reads from the source file which is
TextFile.txt*/
30: WRITE CELL: 1: 1: $$FileRead
;; Writing Column Titles in Excel File
40: WRITE CELL: 2 : 1 : "Name"
50: WRITE CELL: 2 : 2 : "Parent"
60: WRITE CELL: 2 : 3 : "Opening Balance"
;; Looping till the End of File is encountered in the Source Text File "TextFile.Txt"

417
TDL Procedural Capabilities

70 : WHILE : NOT $$FileIsEOF


/*Function 'FileRead' without any parameter reads the entire line. Parameter is the number of characters to be read*/
80 : SET: Text Line : $$FileRead
90 : IF: $$ExactMatch:($$StringPart:##TextLine:0:2):"--"
100: CONTINUE
110: ELSE:
;; If the first 7 characters contain "Printed" then Break the While Loop
120: IF : ($$StringPart:##TextLine:0:7) = "Printed"
130: BREAK
140: ENDIF
150: ENDIF
160: SET : ColCounter: 1
/*Tokenizing the String contained in Variable 'TextLine' for '-' as separator so that one line can be ;;separated into
multiple fields i.e., Name, Group and Opening Balance, since the separator used in ;; Text File is '-'*/
170:FOR TOKEN: TokenVar : ##TextLine: "-"
/*Variables RowCounter and ColCounter are dynamic counters within the loop which determines the Row and Column
where the current value of the variable "TokenVar" will be printed in Excel*/
180: WRITE CELL : ##RowCounter : ##ColCounter: ##TokenVar
190: INCREMENT: ColCounter
200:END FOR
210: INCREMENT: RowCounter
220:END WHILE
;; Closing both source and target files
230: CLOSE FILE
240: CLOSE TARGET FILE
;; Opening the excel file for ease of the user
250: EXEC COMMAND: Excel: "WriteFile.xls"
;; End-of-File

418
TDL Procedural Capabilities

Output

Program Explanation
The function Exer RFT and WTE is used to read from a Text file and write to an Excel file.
So two files are required for successful execution of this program. The action OPEN FILE is
used to open the file “TextFile.txt” in read mode by specifying the parameter as “Read”.
Whereas the file “Writefile.xls” is opened for writing by specifying “Write “. The action
ADD SHEET is used to add a new sheet “From Text File” in the Excel file “WriteFile.xls”
The reading form the “Textfile.txt” is done line by line. The function $$FileRead without any
parameter is used to Read the entire first line and action WRITE CELL is used to write it in
the specified row, column.
The looping construct WHILE is used to loop through the Text File to check for End of File.
The function $$FileIsEOF returns true is the End-Of File is reached. The exit condition for the
loop is when the Text “Printed” is encountered.
The variable “TextVar” is used to store the content of a line. In the text file ‘-‘(hyphen) is used
as a separator for Name, Group and Opening Balance. The looping construct For Token is
used to tokenize the Contents of variable “TextVar” and writing each token in in a cell identi-
fied by the value of variables “RowCounter” and “CollCounter”. The value of these variables
is incremented within the loop to determine the next Row and Column where the next value of
variable “TextVar” will be printed in Excel.

419
Chapter 10: Variable Framework

10.1 The Concept


10.1.1 Introduction
Variables in TDL (Tally Definition Language) are entities which can hold values during the
execution of a program. The values of these variables are initialized when it is created and can
change during the entire execution of program. Program can change the variable value by spec-
ifying expressions which are evaluated and the value of the variables are set.
Variables are context free structures which do not require any specific object context for manip-
ulation. Variables are declared by name and can be operated using the same name. It is also
possible to access and operate variables declared at the parent scope also. Variables are light
weight data structures which are very simple to operate and provide the capability of storing
multiple values of same type and different types as well. It is also possible to perform the
various manipulation operations like insert/update/delete/sort and find. These are mainly used
to perform complex computations.

10.1.2 Types of Variable


Variable can hold a single value, or more than one value of same type or even different types. It
can be declared at various scopes such as Report, Function and System Level. The various
types of variables available in TDL are explained as below.
Simple Variable
Simple variables allow storage of a single value of the specified data type.
Simple Repeat Variables
The Simple Variable can hold method values of multiple objects of a collection based on an
implicit index. This concept is used in Columnar Reports only where the lines should be
repeated vertically and the fields should be repeated horizontally.
Compound Variable
Compound Variables allows us to store values of different data types. This is achieved by
making the variable itself compound, by allowing variable declaration inside itself. These sub
variables are called member variable of the main variable.

421
Variable Framework

A member variable can be a single instance or a list variable. A member variable can be a
compound variable and can have members again, and therefore any hierarchy can be created.
Compound variables help grouping of related information together into one specification.
List Variable
A variable at the declaration time can be either declared as a single instance or as a list. List
variable is a container (data structure) variable and hence they are not defined. Variables can
be declared as list.
List Variable can hold one or more variables which can be either a simple or compound varia-
bles. Each of these is called Element Variables. Element Variable holds value as well as key if
specified. The key is optional, and hence without a key also elements can be added to list vari-
ables. The value of key specified for each of the element variables must be unique.
a. Simple List Variable
Simple Variable can be declared as a list. Simple List Variables can hold multiple values of
single data type.
b. Compound List Variable
Compound Variable can be declared as a list. Compound List Variables can hold multiple
values of different data types.
10.2 Usage

10.2.1 Variable Definition and Attributes


A Variable definition is similar to any other definition. The behavior of the variable is
specified by the programmer via Variable definition.
Syntax
[Variable: <Variable Name>]
Attribute: Value
Where,
<Variable Name> is the name of the variableA meaningful name which determines its purpose
can be given as a variable name.
Let us discuss the attributes of Variable definition in detail:-
Type
This attribute determines the Type of value that will be held by the variable. All the data types
supported by TDL such as String, Number, Date etc., can be used to specify the variable data
type. In the absence of this attribute, a variable assumes to be of the Type String by default.
Syntax
[Variable: <Variable Name>]
Type: <Data Type>

422
Variable Framework

Where,
<Variable Name> is the name of the variable
<Data Type> is primary data type name

Example:
[Variable: GroupNameVar]
Type: String
In this example, a variable which holds the data type of string is defined.

Default
Default value of the variables can be specified during definition using DEFAULT attribute.
This is the initial value which is assigned to the variable when it is instantiated / declared. We
can also specify the default value during declaration / instantiation. The difference is that the
default value specified using this attribute at the definition time will be applicable to all
instances of the variable declared (at any scope). Default value specified while declaration will
be apply only to the specific instance.

Declaration and scope will be covered in detail in the subsequent topics. The
above explanation will be clearer after that.

Syntax
[Variable: <Variable Name>]
Default:<Default Value>
Where,
<Variable Name> is the name of the variable.

Example:
[Variable: GroupNameVar]

Type : String
Default : $$LocaleString:“SundryDebtors”
In this example, the default value for the variable is set as “Sundry Debtors”.

423
Variable Framework

Volatile
If the Volatile attribute in variable definition is set to Yes, then the variable is capable of
retaining previous values from the caller scope. The default value of this attribute is Yes. ie., if
the variable by the same name is declared in the called Report/Function and the volatile
attribute is set to “Yes”, then in the called Report it will assume the last value from the caller
Report. The default value of the attribute Volatile is always “Yes”.
In order to understand it better, let us elaborate the above further. When a variable is declared /
instantiated it assumes a default value. The default value which it assumes is controlled by the
following factors:
1. If volatile is set to “Yes” for a variable in its definition and is instantiated / declared
inside function/report, and the variable by the same name exists in the parent scope,
then it will take its default value from the parent scope. If no variable by the same
name exists in the parent scope, it will take the default value specified within the def-
inition.
2. If default value is specified within the declaration itself, it will assume that value.
If a new report Report2 is initiated, using a volatile variable GroupNameVar, from the current
report Report1, the same variable in Report 2 will have the default value as last value saved in
Report 1. Within Report 2 the variable can assume a new value. Once the previous report
Report1 is returned back from Report2, then the previous value of the variable will be
restored. A classic example of this is a drill down Trial Balance.
Syntax
[Variable: <Variable Name>]
Volatile : <Logical Value>
Where,
<Variable Name> is the name of the variable.
<Logical Value> is either Yes or No.

Example:
[Variable: GroupNameVar]
Type : String
Volatile : Yes

424
Variable Framework

Volatile Attribute of GroupNameVar Variable is set to Yes, which means that Group NameVar
can inherit values from one Report to another.Variables defined at the function level are Non
Volatile by default. They do not inherit the values from the caller scope.

Scope will be discussed in detail in the subsequent topics

Persistent
This Attribute decides the retention periodicity of the variable. i.e till when will it retain the
value, i) till application termination or ii) after application termination as well. Setting the
attribute Persistent to Yes, means that the value saved during the last application session will
be retained permanently in the system. When the next session of Tally is started it will take its
initial value from the value saved in the previous session. i.e., the latest value of the variable
will be retained across the sessions. Variables declared at the system scope can only be
persisted in the default file named tallycfg.tsf which will be available in the folder path
specified for Tally Configuration file. Each time Tally is restarted, these variable values are
accessed from this file.
A List variable at a system scope can also be persisted by specifying the persistent attribute for
its element variable (whether it is simple/compound) within the definition. Inline variables
even at system scope cannot be persisted. We will discuss about inline variable declaration in
the further topics:-
Syntax
[Variable: <Variable Name>]
Persistent : <Logical Value>
Where,
<Variable Name> is the name of the variable
<Logical Value> is either Yes or No.

Example:
[Variable: SV Backup Path]
Type : String
Persistent : Yes
The Attribute Persistent of the variable SV Backup Path has been set to Yes which means that
it retains the latest path given by the user even during the subsequent sessions of Tally.

425
Variable Framework

Persisting Variables in User Specified File


Variables at System Scope and Report scope can also be persisted in to a user specified file.
We will discuss about it in detail under the topic “Variable Declaration and Scope”.

Repeat
The attribute Repeat for a variable is used for its usage in Columnar Reports. It accepts collec-
tion name and optional method name as parameters. Multiple values are stored in the variable
based on an implicit index. Method value of each object of the collection will be picked up
and stored in the variable based on implicit index. In case method name is not specified the
variable name is considered as the method name and picked up from the collection.
Syntax
[Variable: <Variable Name>]
Repeat : <Collection Name>[:<Method Name>]
Where,
<Variable Name> is the name of the variable
<Collection Name> can be an expression which evaluates to a collection name.
<Method Name> is the name of the method whose value needs to be picked up from each
object of the collection. If not specified, variable name is considered as the method name.

Example:
[Variable: SVCurrentCompany]
Volatile : Yes
Repeat : ##DSPRepeatCollection
Let us suppose the variable ‘DSPRepeatCollection’ holds the value “List of Primary Compa-
nies”. Method value ‘SVCurrentCompany’ will be gathered from the each object of the col-
lection and stored in the index 1, index2 and so on.

We will elaborate further about Repeat Attribute under the topic “Implication
of Repeat Variables in Columnar Report”

426
Variable Framework

Variable
The attribute Variable is used to define the member variable (Simple / Compound) for a
Compound Variable.
Syntax
[Variable: <Variable Name>]
Variable : <Variable Names> [:<Data Type>[:<Value>]]
Where,
<Variable Names> is the list of simple or compound variables separated by comma.
<Data Type> is used to specify the data type of simple variable. In case of compound
variable, data type cannot be specified here as it consists of members belonging to various data
types. If the data type is not mentioned, the primary variable definition is mandatory.
<Value> is the default/initial value provided for the variable.
Specifying both <Data Type>and <Value> are optional.

If the data type is specified, then it is called inline declaration of variable. [We will learn about
inline declarations and compound variables further].

Example:
[Variable: CLV Emp]
Variable : Name : String
Variable : Age : Number : 25
Variable : Salary : Amount
Variable : Relatives

In this example, the simple variables Name, Age, Salary and the compound variable ‘Rela-
tives’ are defined as members for the Compound Variable CLV Emp.

List Variable
The attribute List Variable is used to specify a list of either a Simple or Compound Variable.
Syntax
[Variable: <Variable Name>]
List Variable : <Variable Names> [:< Data Type>[:<Value>]]
Where,
<Variable Names> is the list of Simple or Compound Variables separated by comma.

427
Variable Framework

<Data Type> is the data type of Simple Variable. In case of Compound Variable, data type
cannot be specified here as it consists of members belonging to various data types.
<Value> it denotes the no of elements in the list
Specifying both <Data Type>and <Value> are optional.
Example:
[Variable: CLV Emp]
Variable : Name : String
Variable : Age : Number
Variable : Salary : Amount
List Variable : City : String : 3
List Variable : Relatives

[Variable: Relatives]
Variable : Name : String
Variable : Age : Number
Variable : Relation : String
Variable : Salary : Amount
In this example, in addition to simple variables, a simple list variable City and a compound list
variable Relatives are defined as members using the attribute List Variable. A separate defini-
tion is required for the compound list variable Relatives as it holds the multiple values of
different data types. [We will learn about List Variables in the forthcoming topics]

10.2.2 Object Vs Compound Variable


We can think about compound variables as an ‘object’. Following table shows the similarities
between an object and a compound variable.
Object Compound Variable
Can have methods Can have Simple Variable as its mem-
ber
Can have repeated methods (simple Can have a Simple List Variable as its
collections) member

428
Variable Framework

Can have collections (compound col- Can have Compound List Variable as its
lections) member
*Cannot have objects under it Can have a Compound Variable as its
directly* member

We can have a comparison between the internal Data Object ‘Voucher’ and a Compound
Variable ‘CLV Emp’ to understand the similarities between an Object and Compound
Variable. For instance, the Compound Variable ‘CLV Emp’ is defined as below:

[Variable: CLV Emp]


Variable : Name : String
Variable : Designation : String
Variable : Age : Number
Variable : Salary : Amount
List Variable : Contact Nos : String
List Variable : Relatives
Variable : Contact Address

[Variable: Relatives] ;; Defining Compound Variable

Variable : Name : String


Variable : Age : Number
Variable : Relation : String
Variable : Salary : Amount

[Variable: Contact Address] ;; Defining another compound variable

Variable : Street Name : String


Variable : City Name : String

429
Variable Framework

Object : Voucher Compound Variable : CLV Emp


Object “Voucher” is having meth- Compound Variable “CLV Emp” is
ods directly under it such as Date, having Simple Variables such as
Voucher Number, Narration etc. Name, Age, Salary etc.
Voucher is having the repeated CLV Emp is having the Simple List
method BasicBuyerAddress Member Variable ‘Contact Nos’
(Simple Collection)
Voucher is having the collection CLV Emp is having the Compound
“Inventory Entries” (Compound List Member Variable ‘Relatives’
Collection).
Voucher object is not having CLV Emp is having the another
another voucher (primary object) Compound Member Variable
under it directly. ‘Contact Address’

10.2.3 Variable Declaration & Scope


Variables can be declared at various scopes. The availability of the variable within the defini-
tion under which it is declared is called as the scope. The lifetime of the variable will be within
the scope. For example, if the scope of a particular variable is within a function, then the
variable will last till the function is executing and then is destroyed.
Variables can be declared at System, Report and Function scopes. Let us have a detailed look
on the variable scopes.

System
Variables declared at system level will starts its life when the application starts, and will be
alive till the application termination
System variables are declared using a special [System: Variable] definition. The variables
declared at system scope are accessible everywhere in the system.

Syntax
[System: Variable]
Variable Name : <Initial Type Based Value>
Or
Variable : <Variable Names> [:<Data Type>[:<Value>]]

430
Variable Framework

Or
List Variable : <Variable Names> [:<Data Type>[:<Value>]]
Or
Variable : <Instance Names>:[<Variable Name>]
Or
List Variable : <Instance Names>:[<Variable Name>]
Where,
<Initial Type Based Value> is the initial value specified to the variable
<Instance Names> is the list of simple / compound / list variables separated by comma
(instance variables).
<Variable Name> is the simple or compound variable name.

The variables can be declared at the system scope by using the above. The attribute Variable
and List Variable usage is same as described above in the “Variable Definition”.

Example:1
[System : Variable]
BSVerticalFlag : No
The BSVerticalFlag Variable is declared in System Scope. Hence, this variable value being
modified in a Report is retained even after we quit and re-enter the Report.

Example:2
Below is the definition of a Compound Variable “Employee”
[Variable: Employee]
Variable : EmpName : String
Variable : Designation : String
Now we can create a variable instance using the definition of another variable.
[System: Variable]
Variable : Prem : Employee
;; an instance is declared with the name as ‘Prem’ and definition name as ‘Employee’. The variable instance ‘Prem’ will inherit
the entire structure of variable definition ‘Employee’.
Variable : Kamal, Vimal : Employee
;; two instances are declared with the names “Kamal” & “Vimal” and the definition name as “Employee”
List Variable : Employee2 : Employee

431
Variable Framework

;; a List Variable instance is declared with the name “Employee2” and the definition name as “Employee”

Example:3
[System: Variable]
Variable : Employee1 : String : “Suresh”
Variable : Employee2 : Employee1
In this example, we are trying to declare a variable instance ‘Employee2’ which is of type of
another variable ‘Employee1’. This will NOT work because the variable ‘Employee1’ is
declared as inline hence it is not having any defined structure.
Hence, inline variables can not be used to declare another variable instance.

Report
Variables declared at report definition are termed having Report Scope. These variables will
exist till the life of the report.

The variables declared at report scope are accessible from the report itself and all TDL
elements which are executed from within this report such as another report, function etc.
Report variables will get its default value from the definition specification or from the declara-
tion specification or values will be inherited from the owner scope if variable is marked as
volatile.

Report allows two special attributes SET and PRINT SET to set / override the values of the
variable during the startup of the report either in display / print mode respectively.
Form definition also has a SET attribute which overrides the variable’s value during startup
creation and subsequent re-creation of the form during any refresh / regeneration.
We will study about these value specification attributes in detail under the topic “Manipulating
Simple & Compound List Variables”.

Syntax
[Report : <Report Name>]
Variable : <Variable Names>
Or
Variable : <Variable Names> [:<Data Type>[:<Value>]]
Or
List Variable : <Variable Names> [:<Data Type>[:<Value>]]

432
Variable Framework

Or
Variable : <Instance Names>:[<Variable Name>]
Or
List Variable : <Instance Names>:[<Variable Name>]

Where,
<Instance Names> is the list of Simple / Compound / List Variables separated by comma
(instance variables).
<Variable Name> is the Simple or Compound variable name.

The variables can be declared at Report scope by using the above. The attribute Variable and
List Variable usage is same as described above in the “Variable definition”.

Example:
[#Report: Balance Sheet]
Variable : Explode Flag
Explode Flag Variable is made local to Report Balance Sheet by associating it using the Report
attribute ‘Variable’. This variable retains its value as long as we work with this Report. On
exiting the Report, the variable is destroyed and the values are lost.

Function
Function (User Defined Function) also allows the variables to be declared at its scope.
Function variables has lifetime till the end of the execution of the function.
Function variables can also be declared with default value. Function variables will never
inherit the value from the parent context. This means that a volatile attribute on function
variables has no effect. Function allows actions to change the value of the variables.
Function allows a special scope as STATIC. A static variables declared in a function are equiv-
alent to a system variables but can be accessed only within the defined function. Their initial
values are set only during the first call to the function, and later it retains the value for further
calls.
Only simple or compound variables can be declared as static. List variables are not currently
supported at static scope.

Syntax
[Function: <Function Name>]
Variable : <Variable Names>

433
Variable Framework

Or
Variable : <Variable Names> [:<Data Type>[:<Value>]]
Or
List Variable: <Variable Names> [:<Data Type>[:<Value>]]
Or
Variable : <Instance Names>:[<Variable Name>]
Or
List Variable: <Instance Names>:[<Variable Name>]
Or
Static Variable: <Variable Names>[:<Data Type >]
The variables can be declared at Function scope by using the above. The attribute Variable and
List Variable usage is same as described above in the “Variable definition”.

Example:1
[Function : FactorialOf]
Variable : Factorial
The Function ‘FactorialOf’ requires variable ‘‘Factorial’ for calculation within the Function.

Example:2
[Function : Sample Function]
Static Variable : Sample Static Var : Number
The static variable ‘Sample Static Var’ retains the value between successive calls to Function
‘Sample Function’.

Inline Declaration
Variables can also be defined (with limited behavior) during declaration itself, so a separate
definition would not be mandatory. These are called inline variable specification (i.e during
declaration itself the variables are defined inline)
Only the DATA TYPE and the DEFAULT VALUE can be specified as the behavior for inline
variables. If the DATA TYPE is specified as a variable name (i.e., not an implicit data type key
words such as String, Amount etc.,) or is left blank it is treated as pre-defined variables.
Persistence
Inline variables even at system scope cannot be persisted in the system file tallycfg.tsf.
However inline variables at System Scope and Report Scope can be persisted in a User
Specified File using the actions SAVE VARIABLE and LOAD VARIABLE.

434
Variable Framework

Declaring Inline Simple Variable


Variable attribute allows declaring inline Simple Variable by specifying data type. Initial
value to the variable can also be specified optionally.

Syntax
Variable: <Variable Names> [:<Data Type>[:<Value>]]
Where,
<Variable Names> is a list of simple variables separated by comma
<Data Type> is the data type of simple variable
<Value> is the default/initial value provided for the variables and this value specification is
optional

Example:
[Report: Cust Group Report]
Variable: VarGroupName1, VarGroupName2 : String : “Sundry Debtors”
In this example, the Simple Variables VarGroupName1, VarGroupName2 of type string are
declared in a Report hence the following separate variable definitions are not required which
will help to reduce the coding complexity.
[Variable: VarGroupName1]
Type: String

[Variable: VarGroupName2]
Type : String

Declaring Inline Simple List Variable


List Variable attribute allows declaring inline Simple List Variable by specifying the Data
Type. If the default value is specified, it is treated as the count to initialize the list with the
specified elements by default.

Syntax
List Variable : <Variable Names> [: <Data Type> [: <Value>]]
Where,
<Variable Names> is a list of simple variables separated by comma
<Data Type> is the data type of simple variable
<Value> it is treated as the count to initialize the list with the specified elements by default

435
Variable Framework

The number of elements can be specified only for an index based list.

Example:
[System: Variable]
List Variable: VarGroupName1, VarGroupName2 : String : 10
In this example, the variables VarGroupName1 and VarGroupName2 of string data type are
declared as inline simple list variables at system level and each variable will have 10 elements
by default.

Declaring Inline Compound List Variable


For Compound List Variables, definition is mandatory. They cannot be declared inline

Persisting Variables in User Specified File


Variables at declared at System and Report Scope can be persisted in to a user specified file.
This is stored in a standard variable format and also allows reloading System and Report scope
variables from the specified file. The Actions SAVE VARIABLE and LOAD VARIABLE are
used for this purpose.

SAVE VARIABLE
The action SAVE VARIABLE is used to persist the System and Report Scope Variables in a
user specified file.
Syntax
SAVE VARIABLE : <FileName> [:<Variable List>]
Where,
<File Name> is the name of file in which the system scope/ report scope variables are per-
sisted. The extension .PVF will be taken by default if the file extension is not specified.
<Variable List> is the list of comma separated variables that need to be saved in the file.The
special character * also can be used to specify the variable list which means all at 'current
scope'.When * is used, it will ignore the persist flag and save all variables in the scope.
Leaving this parameter as BLANK will persist all the variables which are set “Persist:Yes” at
variable definition level.
Dotted notation syntax is also supported in the variable list specification. However this cannot
be used for SUB variables. This can be used only for accessing parent scope variables.

LOAD VARIABLE
The action LOAD VARIABLE is used to reload the System and Report Scope variables from
the specified file.

436
Variable Framework

Syntax
LOAD VARIABLE : <FileName> [:<Variable List>]
Where,
<File Name> is the name of file in which the system scope/ report scope variables are per-
sisted. Specifying file extension is mandatory while loading variable values.
<Variable List> is a list of comma separated variables that need to be loaded from the file.
While loading * i and ‘Persist’ flag of the variable are ignored. It is assumed that the variable
must have a persist flag OR it is saved forcefully and hence to be loaded.

Example:1
There is a requirement to persist values of all system scope variables in a user specified file
and load the values from the file whenever required. Refer to the below code snippet:-
[#Menu: Gateway of Tally]
Add: Button : SLSystemScopeSave, SLSystemScopeLoad
Buttons SLSystemScopeSave & SLSystemScopeLoad are added at the Gateway of Tally
Menu to execute the actions SAVE VARIABLE & LOAD VARIABLE.
[Button: SLSystemScopeSave]
Key : Alt+F
Action : SAVE VARIABLE : SLSystemScope.pvf : *
Title : "Save Sys Var"
Values of all system scope variables will be persisted in the file SLSystemScope.pvf on
execution of the action SAVE VARIABLE.
[Button: SLSystemScopeLoad]
Key : Alt + L
Action : LOAD VARIABLE : SLSystemScope.pvf
Title : "Load Sys Var"
Values of all system scope variables will be loaded from the file SLSystemScope.pvf on
execution of the action LOAD VARIABLE.

Example: 2
There is a requirement to persist values of all system scope variables which are set “Persist :
Yes” at variable definition level in a user specified file and load the values from the file
whenever required. Refer to the below code snippet:

437
Variable Framework

[#Menu: Gateway of Tally]


Add : Button : SLSystemScopeSave, SLSystemScopeLoad
Buttons SLSystemScopeSave & SLSystemScopeLoad are added at the Gateway of Tally
Menu to execute the actions SAVE VARIABLE & LOAD VARIABLE.
[Button: SLSystemScopeSave]
Key : Alt+F
Action : SAVE VARIABLE : SLSystemScope.pvf
Title : "Save Sys Var"
Values of all variables at system scope which are set “Persist : Yes” at variable definition level
will be persisted in the file SLSystemScope.pvf on execution of the action SAVE VARIABLE.
[Button : SLSystemScopeLoad]
Key : Alt + L
Action : LOAD VARIABLE : SLSystemScope.pvf
Title : "Load Sys Var"
Values of all variables will be loaded from the file SLSystemScope.pvf on execution of the
action LOAD VARIABLE.

Example:3
There is a requirement to persist the system scope variables SVSymbolInSign & SVInMillions
in a user specified file and load values of these variables from the file whenever required.
Refer to the below code snippet:-
[#Menu: Gateway of Tally]
Add : Button : SLSystemScopeSave, SLSystemScopeLoad
Buttons SLSystemScopeSave & SLSystemScopeLoad are added at the Gateway of Tally
Menu to execute the actions SAVE VARIABLE & LOAD VARIABLE.
[Button: SLSystemScopeSave]
Key : Alt+F
Action : SAVE VARIABLE : SLSystemScope.pvf : SVSymbolInSign, +
SVInMillions
Title : "Save Sys Var"
Values of the system scope variables SVSymbolInSign & SVInMillions will be persisted in
the file SLSystemScope.pvf on execution of the action SAVE VARIABLE.

438
Variable Framework

[Button: SLSystemScopeLoad]
Key : Alt + L
Action : LOAD VARIABLE : SLSystemScope.pvf : SVSymbolInSign, +
SVInMillions
Title : "Load Sys Var"
Values of the system scope variables SVSymbolInSign & SVInMillions will be loaded from
the file SLSystemScope.pvf on execution of the action LOAD VARIABLE.

Example: 4
Let us suppose the following report is displayed in Create mode from a menu item.
[Report: Smp SLReport]
Form : Smp SLForm
Variable : SaveLoadVar1, SaveLoadVar2
The variables SaveLoadVar1 & SaveLoadVar2 are declared at Report Scope.
[Form: Smp SLForm]
Parts : Form SubTitle, Smp SL Part
Button : Smp SaveVar, Smp LoadVar
Buttons SmpSaveVar & SmpLoadVar are added at Form Level to execute the actions SAVE
VARIABLE & LOAD VARIABLE.

Let us look in to the below scenarios to persist & load System Scope as well as Report Scope
Variable values:-
i)Persist & Load all Report Scope Variables & a specific System Scope Variable
[Button: Smp SaveVar]
Key : Alt + S
Action : SAVE VARIABLE: SLReportCfg.pvf: *,().SVInMillions
Title : "Save Variable"
Values of all variables declared at report scope and the value of system scope variable SVIn-
Millions will be persisted in the file SLReportCfg.pvf on execution of the action SAVE
VARIABLE. (The variable SVInMillions is prefixed with (). to denote the same as System
Scope Variable).
[Button: Smp LoadVar]
Key: Alt + L
Action: LOAD VARIABLE : SLReportCfg.pvf : *,().SVInMillions

439
Variable Framework

Title: "Load Variable"


Variable list specification* will be ignored. Values of all report scope variables and the value
of system scope variable SVInMillions will be loaded from the file SLReportCfg.pvf on
execution of the action LOAD VARIABLE.

ii)Persist & Load a specific Report Scope variable & a specific System Scope variable
[Button: Smp SaveVar]
Key : Alt + S
Action : SAVE VARIABLE : SLReportCfg.pvf : SaveLoadVar1,+
().SVInMillions
Title : "Save Variable"
Value of Report scope variable SaveLoadVar1 and value of system scope variable SVIn-
Millions will be persisted in the file SLReportCfg.pvf on execution of the action SAVE
VARIABLE.
[Button: Smp LoadVar]
Key : Alt + L
Action : LOAD VARIABLE : SLReportCfg.pvf : SaveLoadVar1,+
().SVInMillions
Title : "Load Variable"
Value of Report scope variable SaveLoadVar1 and value of system scope variable SVIn-
Millions will be loaded from the file SLReportCfg.pvf on execution of the action LOAD
VARIABLE.

10.2.4 Using Modifiers with Variables


Variable allows static modifiers such as Add/Delete/Change and Dynamic modifier ‘Local’.

Static Modification
Add / Delete / change modifiers can be used on variables to change the behavior.

Example:
[#Variable : SV From Date]
Delete: Default

440
Variable Framework

Dynamic Modification
When different reports require the same Compound Variable and some modifications are
required specific to respective reports like adding additional members (local to the report) are
possible through the Dynamic Modifier ‘Local’.

Example:
In our example, we have defined a Compound Variable CLVEMP as below
[Variable: CLV Emp]
Variable : Name : String
Variable : Designation : String
Variable : Age : Number
Variable : Salary : Amount
List Variable : Contact Nos : String
List Variable : Relatives
Variable : Contact Address

[Variable: Relatives] ;; Defining Compound List Variable


Variable : Name : String
Variable : Age : Number
Variable : Relation: String
Variable : Salary : Amount

[Variable: Contact Address] ;; Defining another compound List Variable

Variable : Street Name : String


Variable : City Name : String
In ‘Employee Report1’, the variable is declared and no modifications are required locally.
[Report: Employee Report1]
Variable: CLV EMP
In ‘Employee Report2’, the same variable is declared but locally a member variable is added
and an existing member variable is deleted.

441
Variable Framework

[Report: Employee Report2]


Variable : CLV EMP
Local : Variable : CLV EMP : Add : Variable : Qualification: String
Local : Variable : CLV EMP : Delete : Variable : Age
Also member variables can be localized within a compound variable. This provides the ability
to re-use a compound structure defined earlier and do any local modifications as required.

Example:
[Variable: CLVEMP]
Variable: Contact Address
Local : Variable: Contact Address : Add : Variable : State : String

10.2.5 List Variable Manipulations


Simple and Compound List variables support various data manipulation operations such as
Adding / Deleting / Expanding List elements, Value Specifications, Retrieving values from the
list elements, Searching and Sorting, Populating List Variable from a Collection, etc. New
Actions and Functions specific to List Variables are introduced for these manipulations.
Before look in to these manipulations, let us understand the concept of Key, Index and
Variable Path Specificaton using Dotted Notation Syntax.

Concept
Key
List variables can hold multiple values of the variable type using a string based ‘Key’ specifi-
cation. 'Key' is of type String by default. We can specify a different datatype for a key only in
scenarios where we require key based sorting. It is optional to specify the key value while
adding values to the list variable. The TDL Programmer has to explicitly specify the key
value. Key is unique for all elements in the list. If an element is added with duplicate key, then
the existing element is over written.
It is advisable to use a key only when we require frequent access to the elements of the list
based on a key.

Index
An element of the list can be accessed via ‘Index’. Index of an element is the location/position
of the variable from the first element in the current sorting order. Even if we have specified
keys for elements of a list, index is generated internally. It is always possible to access each
element in the list by specifying the index within square brackets [] in the dotted notation

442
Variable Framework

syntax. This is explained below. Index can be negative as well. In that case it is possible to
access the elements in the reverse order of entry.

Variable Path Specification using Dotted Notation Syntax


Compound Variables allows us to store values of different data types. A member variable can
be a single instance or a list variable. A member variable can be a compound variable and can
have members again, and therefore any hierarchy can be created. In short, it is similar to a
Data Object.
Hence all the attributes and actions which operate variable will take the variable path syntax.
i.e., variable path can be specified using dotted notation syntax. The syntax can be used to
fetch any value from any member within the hierarchy. This syntax is applicable wherever we
need to specify either the variable identifier or access the value of the variable. In case of value
access the operator ## is used. Value access using operator ## is discussed in detail in the
topic Index Based Retrieval using ## Operator

Syntax
<Element Variable Specification>.<Member Variable Specifica-
tion>.< Simple Member Value specification>
Where,
<Element Variable Specification> can be a compound variable or compound list variable
[Index Expression]
<Member Variable Specification>can be a compound variable member or compound list
member variable [Index Expression]
<Simple Member Value Specification> refers to the name of the simple member in the
specified path
<Index Expression>can be an expression that evaluates to number. Suffixing a variable with
index refers to an element variable. This can be positive or negative. Negative index denotes
reverse access.

Example:
The below compound variable is defined:-
[Variable: CLV Emp]
Variable : Name : String
Variable : Age : Number
Variable : Salary : Amount
List Variable : Relatives

443
Variable Framework

[Variable: Relatives]
Variable : Name : String
Variable : Age : Number
Variable : Relation : String
Variable : Salary : Amount
The same is declared at the System Scope, hence the same can be accessed anywhere in the
system.
[System: Variable]
List Variable : CLV Emp

Example:1
Suppose, we want to set the value of a simple variable ‘Employee Name’ which is declared at
Report Level
[Report: Employee Report]
Variable : Employee Name : String
SET : Employee Name : ##CLVEMP[1].Name
The variable Employee Name will be set with the value of member “Name” of the first
element of the Compound List Variable “CLVEMP”

Example: 2
In case we need to a display the age of first relative of the second employee we would use the
following statement in a field in a report
[Field: RelAge]
Set As : ##CLVEMP[2].Relatives[1].age
We will discuss in detail regarding the value specification attributes and actions with the
enhanced variable path specification in the further topics.

Scope specification in Dotted Notation Syntax for variables


The Dotted Notation Syntax for Variables (##) allows specification of scope / relative scope
etc.
Syntax
.. (DOUBLE DOT) denotes owner scope
... (TRIPPLE DOT) denotes owner’s owner scope and so on
(). denotes a system scope

444
Variable Framework

(<Definition Type>, <Definition Name Expression>). can be used to specify an absolute


scope specification.
The element (<Definition Type>, <Definition Name Expression>) has to be in the current
execution chain else one will not be able to refer the same.

Where,
<Definition Type> is the name of the definition such as Report, Function etc. in the current
execution chain.
<Definition Name Expression> can be an expression which evaluates to a definition name.
The Definition Name Expression is optional.

Exercise 9.1:
Objective
The objective of this program is to understand the scope of variable and extract value from
variables in different scopes

Capabilities Used
 Scope specification in Variable Dotted Syntax at Field Level
Code:
[Function: Exer Variable Scopes]
VARIABLE : Exer Variable ;; Variable declared within Function Scope

00 : SET : Exer Variable : "This is Function scope value"


10 : DISPLAY : Exer Variable Scopes

[Report: Exer Variable Scopes]


Form : Exer Variable Scopes
Variable : Exer Variable ;; Variable declared within Report Scope
Set : Exer Variable : "This is Report scope value"
Title : "Variable and its scope"

[Form: Exer Variable Scopes]


Parts : Form SubTitle, Exer Variable Scopes
Width : 80% Page

445
Variable Framework

Local : Field : Form SubTitle : Info : "Variable and its scope"


Local : Field : Form SubTitle : Width : 50% Page

[Part: Exer Variable Scopes]


Lines : Exer VS Title, Exer VS Syntax, Exer VS Details
CommonBorder : Yes
Border : Thin Bottom

[Line: Exer VS Title]


Use : Exer VS Details
Local : Field : Default : Align : Centre
Local : Field : Default : Style : Normal Bold
Local : Field : Exer VS Current : Info : "Current Scope"
Local : Field : Exer VS Owner : Info : "Owner Scope"
Local : Field : Exer VS System : Info : "System Scope"
Local : Field : Exer VS Absolute: Info : "Absolute Spec Report +
Scope"
Border: Thin Top

[Line: Exer VS Syntax]


Use : Exer VS Details
Local : Field : Default: Align : Centre
Local : Field : Default: Style : Normal Italic
Local : Field : Exer VS Current : Info : "##<Variable>"
Local : Field : Exer VS Owner : Info : "##..<Variable>"
Local : Field : Exer VS System : Info : "##().<Variable>"
Local : Field : Exer VS Absolute: Info : "##(Report).<Variable>"
Border: Thin Bottom

[Line: Exer VS Details]


Fields : Exer VS Current, Exer VS Owner, Exer VS System, +
Exer VS Absolute
Local : Field : Default : Align : Centre
Local : Field : Default : Style : Normal

446
Variable Framework

[Field: Exer VS Current]


Use : Name Field
/*The Symbol Prefix ## with a Variable, retrieves the value from a variable within the current scope which is Report*/
Set As : ##ExerVariable
Width : 25% Page

[Field: Exer VS Owner]


Use : Name Field
/* ##.. is used to retrieve the Variable value from the Parent scope which is the Function in this case*/
Set As : ##..ExerVariable
Border : Thin Left Right
Width : 25% Page

[Field: Exer VS System]


Use : Name Field
/* ##(). is used to retrieve the Variable value from the System scope */
Set As : ##().ExerVariable
Border : Thin Left
Width : 25% Page

[Field: Exer VS Absolute]


Use : Name Field
/* ##(Report). is the absolute specification which is used to retrieve the Variable value from the Report scope */
Set as : ##(Report).ExerVariable
Border : Thin Left
Width : 25% Page

[Variable: Exer Variable]


Type : String

[System: Variable]
/* Variable declared at System Scope */
Exer Variable : "This is System scope value"

447
Variable Framework

Output

Program Explanation
In this exercise, the Function Exer Variable Scopes is called from a Menu and the report
“Exer Variable Scopes” is displayed from the Function Exer Variable Scopes. Hence, the
current execution chain is Menu > Function Exer Variable Scopes > Report Exer Variable
Scopes.
A variable Exer Variable is defined and declared at the System Scope. The Same Variable is
declared and the value for the variable set both at Function and Report Level.
The report Exer Variable Scopes displays the value of the variables of different scopes such
as Current Scope (Report), Owner Scope (Function), System Scope etc. Variable values are
extracted at the field level by specifying scope /relative scope and absolute scope specifica-
tion.

List Variable Manipulations – A Detailed Look


Let us have a detailed look on List Variable manipulations with examples:
 Adding / Deleting / Expanding Elements
 Adding Elements to the List Variable

Adding Elements to List Variable


 Action LIST ADD
The Action LIST ADD is used on a list variable to add an element to the list variable based on
KEY. This is mandatory before we set value into the element. KEY is compulsory in this case.
Key is unique for all elements in the list. If an element is added with duplicate key, then the
existing element is over written.The actions LIST APPEND & LIST SET are aliases for the
action LIST ADD.

Syntax
LIST ADD : <List Variable Specification> : <Key Formula> +
[:<Value Formula>[:<Member Specification>]]
Where,
< List Variable Specification > is the simple list or compound list variable specification

448
Variable Framework

<Key Formula> can be an expression which evaluates to unique string value.


<Value Formula> can be an expression which returns a value. It sets the initial value of the
element variable and it is optional.
<Member Specification> this specification is required only if the value needs to be added to a
specific member of a compound list variable. If member specification is not provided the first
member variable is considered for the value.
To add multiple values dynamically to the List variable, we can use LIST ADD within a
looping construct like While…Walk Collection etc.

Example:
Adding elements to Simple List Variable
1. Adding an element to Simple List Variable SLV Emp with a Key

LIST ADD : SLV Emp : “E001”

2. Adding an element to Simple List Variable SLV Emp with a Key and a value

LIST ADD : SLV Emp : “E001” : “Kumar”

3. Adding an element to Simple List Variable SLV Emp with a Key and a value and sub-
sequently overriding a value corresponding to a particular key

LIST ADD : SLV Emp : “E001” : “Kumar”


LIST SET : SLV Emp : “E001” : “Keshav”
Where the value corresponding to a Key ‘E001’ is changed to Keshav

Adding Elements to Compound List Variable


A Compound Variable CLV Emp is defined below which stores the employee details such as
Name, Age, Salary and the details of the Relatives.
[Variable: CLV Emp]
Variable: Name : String ;;simple member variable

Variable: Age : Number ;;simple member variable

Variable: Salary : Amount ;;simple member variable

List Variable : Relatives ;;compound list member variable

449
Variable Framework

[Variable: Relatives] ;; Compound Variable is defined here


Variable: Name: String
Variable: Age: Number
Variable: Relation: String
Variable: Salary: Amount
The same is declared at the System Scope, hence the same can be accessed anywhere in the
system.

[System: Variable]
List Variable : CLV Emp

1. Adding an element to Compound List Variable CLV Emp with a Key

LIST ADD : CLVEmp : “E001”


2. Adding an element to Compound List Variable CLV Emp with a Key and a Value

LIST ADD : CLVEmp : “E001” : “Kumar”


In this example, since the member specification is not provided the first member variable is
considered for the value.
3. Adding an element to Compound List Variable CLV Emp with a Key and a value
with member specification

LIST ADD: CLVEmp: “E001”: 25: Age


In this example, we have provided the member specification, hence the member variable Age
is considered for the value.
4. Adding an element to the Compound List Member of a Compound List Variable with
a Key and a value with member specification

LIST ADD: CLVEmp[1].Relatives: “R001”: “Prem” : Name


In this example, we are adding an element to the Compound List Variable “Relatives” and the
member variable ‘Name’ is considered for the value. ‘Relatives’ is a Compound List Member
variable of the Compound List Variable CLVEMP.

450
Variable Framework

The values are hard coded in the examples for explanation purpose. The above
Simple & Compound List Variable examples are used to explain further list
variable manipulations.

 Action LIST ADD EX


The action LIST ADD EX is used on a list variable to add an element to the list variable
without KEY. The action LIST APPENDEX is an alias for the action LIST ADDEX
Syntax
LIST ADD EX : <List Variable Specification> [:<Value Formula> +
[:<Member Specification>]]
Where,
< List Variable Specification > is the simple list / compound list variable specification
<Key Formula> can be an expression which evaluates to a unique string value.
<Value Formula> can be an expression which returns a value. It sets the initial value of the
element variable and it is optional.
<Member Specification> this specification is required only if the value needs to be added to a
specific member of a compound list variable. If member specification is not provided the first
member variable is considered for the value.
Adding elements to Simple List Variable
1. Adding an element to Simple List Variable SLV Emp

LIST ADD EX : SLV Emp


2. Adding an element to Simple List Variable SLV Emp with Value

LIST ADD EX : SLV Emp : “Kumar”

Adding elements to Compound List Variable


1. Adding an element to Compound List Variable CLV Emp

LIST ADD EX : CLV Emp


2. Adding an element to Compound List Variable CLV Emp with value

451
Variable Framework

LIST ADD EX : CLV Emp : “Kumar”


In this example, since the member specification is not provided the first member variable is
considered for the value.
3. Adding an element to Compound List Variable CLV Emp with value and member
specification

LIST ADDEX : CLVEmp : 25 : Age


In this example, we have provided the member specification, hence the member variable
‘Age’ is considered for the value.
4. Adding an element to the Compound List Member variable of a Compound List Var-
iable with value and member specification

LIST ADDEX : CLVEmp[1].Relatives : “Prem” : Name


In this example, we are adding an element to the Compound List Variable “Relatives” and the
member variable ‘Name’ is considered for the value. ‘Relatives’ is a Compound List Member
variable of the Compound List Variable CLVEMP.

Deleting Elements from the List Variable


 Action LIST DELETE
The Action LIST DELETE is used to delete an element from the list based on Key. Key
formula is optional, if not specified the all the elements in the list are deleted.The Action LIST
REMOVE is an alias for the action LIST DELETE
Syntax
LIST DELETE : < List Variable Specification > [ : <Key
Formula>]
Where,
<List Variable Specification > is the simple list or compound list variable specification
<Key Formula> can be an expression which evaluates to unique string value. It is optional.

Example:
Deleting elements from Simple List Variable
1. Deleting a single element from a Simple List Variable

LIST DELETE : SLV Emp : “E001”


The element identified by key ‘E001’ will be deleted from the Simple List Variable “SLV
Emp” on execution of the action.

452
Variable Framework

2. Deleting all elements from a Simple List Variable

LIST DELETE : SLV Emp


Since the key formula is not specified, all the elements from a Simple List Variable “SLV
Emp” will be deleted on execution of the action.

Deleting elements from a Compound List Variable


Deleting elements from a Compound List Variable is similar to deleting elements from Simple
List Variable.

1. Deleting an element from a Compound List Variable

LIST DELETE : CLV Emp : “E001”


The element identified by key ‘E001’ will be deleted from the Compound List Variable “CLV
Emp” on execution of the action.
2. Deleting all elements from a Compound List Variable

LIST DELETE : CLV Emp


Since the key formula is not specified, all the elements from the Compound List Variable
“CLV Emp” will be deleted on execution of the action.
 Action LIST DELETE EX
The Action LIST DELETE is used to delete an element from the list based on index. INDEX
formula is optional, if not specified then all the elements in the list are deleted. A negative
index denotes reverse position. LIST REMOVE EX is the alias for the action LIST DELETE
EX.
Syntax
LIST DELETE EX : <List Variable Specification> [ : <Index
Formula>]
Where,
<List Variable Specification> is the simple list or compound list variable specification
<Index Formula> can be an expression which evaluates to an index number. It is optional.
Example:
Deleting Elements from Simple List Variable
1. Deleting a single element from a Simple List Variable

LIST DELETE EX : SLV Emp : 2

453
Variable Framework

The element identified by the index number ‘2’ will be deleted from the Simple List Variable
“SLV Emp” on execution of the action.
2. Deleting all elements from a Simple List Variable

LIST DELETE EX : SLV Emp


Since the index formula is not specified, all the elements from a Simple List Variable “SLV
Emp” will be deleted on execution of the action.

Deleting elements from a Compound List Variable


Deleting elements from a Compound List Variable is similar to deleting elements from Simple
List Variable.
1. Deleting an element from a Compound List Variable

LIST DELETE EX : CLV Emp : 10


The element identified by the index ‘10’ will be deleted from the Compound List Variable
“CLV Emp” on execution of the action.
2. Deleting all elements from a Compound List Variable

LIST DELETE EX : CLV EMP


Since the index formula is not specified, all the elements from the Compound List Variable
“CLV EMP” will be deleted on execution of the action.

Expanding Elements in the List Variable


 Action LIST EXPAND
The Action LIST EXPAND is used to create specified number of blank elements and insert
into the list. All these elements are created without a key. If key specification is required for
each element, then either a LIST FILL or a loop can be used to add elements individually.
Syntax
LIST EXPAND : <List Variable Specification> : <Count Formula>
Where,
<List Variable Specification> is the simple list or compound list variable specification
<Count Formula> can be an expression which evaluates to a number.

Example:
1. Expanding Simple List Variable

454
Variable Framework

LIST EXPAND : SLVEMP : 10


In this example, the count formula is 10. Hence, the 10 blank elements added to the Simple
List Variable ‘SLVEMP’.
2. Expanding Compound List Variable

LIST EXPAND : CLVEMP : 5


In this example, the count formula is 5. Hence, the 5 blank elements added to the Compound
List Variable ‘SLVEMP’.

LIST EXPAND : CLVEMP[1].Relatives : 10


In this example, the count formula is 10. Hence 10 blank elements added to the Compound
List Variable ‘Relatives’. ‘Relatives’ is a Compound List Member variable of the Compound
List Variable CLVEMP.

Value Specifications

The value for the Simple / List Variables (Simple & Compound) can be specified using the
Attributes at Report and Form Level and using Actions at User Defined Functions.

 Report Level

The attributes SET and PRINTSET are used to specify the variable values at Report Level.

Attribute “SET”
The Report attribute SET can be used to specify a variable name and its value, which will be
set during the startup of the report.

Syntax
SET : <Variable Specification> : <Value Expression>
Where,
<Variable Specification> is the variable path specification
<Value Expression> can be an expression which evaluates to a value to the variable of the
specified data type.

455
Variable Framework

Example:

SET : Var : “ABC” ;; Setting value to Simple Variable

SET : ListVar[1] : “XYZ” ;; Setting value to Simple List Variable element

SET : CLVEmp[1].Name : “Kumar” ;; Setting value to Compound List Variable element’s member

Attribute “PRINT SET”


The Report attribute Print Set is similar to SET attribute but sets the value of the variables to
specified value when the report is started in print mode.

Syntax
PRINT SET : <Variable Specification> : <Value Expression>
Where
<Variable Specification> is the variable path specification
<Value Expression> can be an expression which evaluates to a value to the variable of the
specified data type.

Example:
PRINTSET : Var: “ABC” ;; Setting value to Simple Variable

PRINTSET : ListVar[1] : “XYZ” ;; Setting value to Simple List Variable element

PRINTSET : CVEmp[1].Name:“Kumar” ;; Setting value to Compound List Variable element’s member

 Form Level

Attribute “SET”
The Form attribute ‘SET’ is similar to Report SET attribute, while report sets the value once in
its life time, the form SET is executed during every regeneration / refresh of the report.

Syntax
SET : <Variable Specification> : <Value Expression>
Where,
<Variable Specification> is the variable path specification
<Value Expression> can be an expression which evaluates to a value to the variable of the
specified data type.

456
Variable Framework

Example:
SET: Var : “ABC” ;; Setting value to Simple Variable

SET: ListVar[1] : “XYZ” ;; Setting value to Simple List Variable element

SET: CVEmp[1].Name: “Kumar” ;; Setting value to Compound List Variable element’s member

 Function Level

The actions SET, MULTISET, INCREMENT,DECREMENT and EXCHANGE are used to


specify the variable values.

Action SET
Values of variables can be set / updated via the SET action. This action is available as a global
action, and can be used within a function also.
List variables and compound variables cannot have values; they can have only element /
member variables inside it respectively.
If SET action is used on compound variables the value will be set to the FIRST member
variable. If the first member variable is again compound program would search first non-
compound leaf member and set the value.
For list variables the value is treated as the count, and the list is expanded by the number of
elements provided in the expression.

Syntax
SET : <Variable Specification> :<Value Expression>
Where
<Variable Specification> is the variable path specification
<Value Expression> can be an expression which evaluates to a value to the variable of the
specified data type.
Example:
SET : Var : “ABC” ;; Setting value to Simple Variable

SET : SLVEMP[1] : “XYZ” ;; Setting value to Simple List Variable element

SET : CLVEmp[1].Name : “Kumar” ;; Setting value to Compound List Variable element’s member
Action MULTISET
The action MULTI SET is used to set values of compound member variables in one call.
All member specifications are relative from the compound variable specification given.

457
Variable Framework

Syntax
MULTI SET : <CompoundVariable Specification>
: <Member Specification : Value> [, <Member Specification
: Value>, …]
Where,
<Compound Variable Specification> is the compound variable specification
<Member Specification : Value> list of name-value pair for setting member values

Example:
MULTISET : CLVEMP[1]: Name :”Vimal”,Age : 26, Salary : =
($$AsAmount:10000)
In this example, all the member variables for the first element of the Compound List Variable
CLVEMP are set using the MULTISET Action.

MULTISET : CLVEMP[1].Relatives[1] : Name : “Hari”, Age:20, +


Relation:“Brother”
In this example, all the member variables for the first element of the Compound List Variable
Relatives are set using the MULTISET Action. Relatives is a Compound List Member
variable of the Compound List Variable CLVEMP.

Action EXCHANGE
The Action Exchange can be used to swap the values between two variables provided both
belong to the same data type.

The same cannot be done for the Simple List or Compound List as a whole. However, value of
an element of Simple List and Compound List Member Variable belonging to same data type
can be exchanged
Syntax
EXCHANGE : <First Variable Specification> : <Second Variable +
Specification>
Where,
<First Variable Specification> is the simple variable specification
<Second Variable Specification> is the simple variable specification

458
Variable Framework

Example:
 Exchanging value of a Simple Variable to another Simple Variable
EXCHANGE : EmpVarOld: EmpVarNew
Both the variables are of String data type. The value of the variable EmpVarOld is exchanged
to the variable EmpVarNew on execution of the action.
 Exchanging value of an element of Simple List Variable to the element of another
Simple List Variable
EXCHANGE: SlvEmpOld[1] : SlvEmpNew[1]
The value of the first element of SlvEmpOld is exchanged to the first element of the SlvEmp-
New. Both the Simple List Variables are of String data type
 Exchanging value of a Simple Variable to a member variable of a Compound List
Variable
EXCHANGE : EMP Salary : CLVEmp[1].Salary
In this example, the value of a variable Emp Salary is exchanged to the member variable
Salary of the Compound List Variable CLVEmp. Both the simple variables are of string data
type.

Action INCREMENT
Increment is a special action provided in function scope to increment values of the variable.
This is supported only on simple variables of type number. The action INCR is an alias for the
action INCREMENT.
Syntax
INCREMENT : <Simple Variable Specification> [: <NumIncrement
Expression>]
Where,
<Simple Variable Specification> is the simple variable specification
<NumIncrement Expression> can be an expression which evalues to a number. Based on
this, variable value will be incremented. It is optional. If not specified, the variable value will
be incremented by 1.

Example:
INCREMENT : Counter ;; Incrementing the variable value by 1

INCR : Counter : 2 ;; Incrementing the variable value by 2

459
Variable Framework

Action DECREMENT
Decrement is a special action provided in function scope to decrement values of the variable.
This is supported only on simple variables of type number.The action DECR is an alias for the
action DECREMENT.

Syntax
DECREMENT :< Simple Variable Specification> [:< NumIncrementEx-
pression>]
Where,
<SimpleVarSpecification> is the simple variable specification
<NumIncrementExpr> can be an expression which evalues to a number. Based on this,
variable value will be decremented. It is optional. If not specified, the variable value will be
decrementd by 1.
Example:
DECREMENT : Counter ;; Decrementing the variable value by 1

DECR : Counter : 2 ;; Decrementing the variable value by 2

 Field Level

Attribute MODIFIES
The Field attribute Modifies is used to modify the value of the variable.
Syntax
Modifies : <Variable Specification>[:<Logical Flag> +
[:<Expression>]]
Where,
<Variable Specification> is the variable path specification
<Logical Flag> can be a logical value TRUE/FALSE. TRUE would set the value after the
field’s acceptance, and FALSE will set during the acceptance of the report having the field.
<Expression> can be an expression which evaluates to a value
Example:
[Field: VarModify Field]
Use : Name Field
Variable : VarModified
Modifies : VarModified: Yes: # VarModifyField + " -" +
##SVCurrentCompany

460
Variable Framework

Let us suppose the value entered in the field is PartyName and the current company name is
ABC Company Ltd. Value of the variable VarModified will be modified as Partyname-ABC
Company Ltd after accepting the field.

10.2.6 Variable copy


The content of variable can be entirely copied from one instance to another instance.

Action COPY VARIABLE


The action COPY VARIABLE is used to copy the content from one variable (Source) to
another variable (Destination). This action is supported for all types of variables (Simple /
Compound / List Variables).
Syntax
COPY VARIABLE: <Destination Variable> :< Source Variable>
Where,
<Destination Variable> is the name of Simple/Compound/List Variable
<Source Variable> is the name of Simple/Compound/List Variable from which the content
has to be copied
Example:
Copying from Simple Variable to Simple Variable
[Function: SimpleVar Copy Function]

VARIABLE : SimpleVar1 : String : "Employee1"


VARIABLE : SimpleVar2 : String :

10 : COPY VARIABLE : SimpleVar2 : SimpleVar1

In this example, the variables SimpleVar1 and SimpleVar2 are declared at the Function level.
After execution of the action COPY VARIABLE the content of the variable copied from
SimpleVar1 to SimpleVar2.
Copying from Compound Variable to Compound Variable. Let us suppose, the below
compound variables are defined:

[Variable: Employee1]
Variable : EmpName : String : "Praveen"
Variable : Designation: String : "Manager"

461
Variable Framework

[Variable: Employee2]
Variable : EmpName : String
Variable : Designation: String

In the below function, we are copying the contents from the Compound Variable Employee1
to Employee2

[Function: Compound Var Copy Function]


VARIABLE : Employee1
VARIABLE : Employee1
10 : COPY VARIABLE : Employee2 : Employee1

The content will be copied from a member variable of Compound Variable


(Source) to another member variable of compound variable (Destination)
based on the member variable names since more than one member variable
may have the same data type.

10.2.7 Copying from List Variable to List Variable


Let us suppose, the below compound variables are defined:-
[Variable: Employee1]
Variable : EmpName : String
Variable : Designation: String

[Variable: Employee2]
Variable : EmpName : String
Variable : Designation: String
In the below function, the compound variables Employee1 and Employee2 are declared as List
Variable. We are copying all the elements from the compound list variable Employee1 to the
compound list variable Employee2.

[Function: ListVar Copy Function]


LIST VARIABLE :Employee1, Employee2

462
Variable Framework

10 : LIST FILL : Employee1 : Employees : $Name : $Name


20 : LIST FILL : Employee1 : Employees : $Name : +
$Designation:Designation
30 : COPY VARIABLE : Employee2 : Employee1
Retrieving value from List
$$ListValue
The function ListValue is used to retrieve value of an element in the list for a given key. If the
list is of compound variables an optional member specification can be provided to extract
value of a specific member.
Syntax
$$ListValue:<List Variable Specification>:<Key Formula>+
[:<Member Specification>]
Where,
<List Variable Specification> is the simple list or compound list variable specification
<Key Formula> can be an expression which evaluates to a string value
<Member Specification> member specification is required only if the value needs to be
extracted from a specific member of a compound list variable
Example:
Retrieving value from Simple List Variable
$$ListValue:SLVEMP: “E001”
In this example, the function returns the value of the element identified by the key ‘E001’
from the simple list variable ‘SLV Emp’.

$$ListValue:SLVEMP:##KeyVar

In this example, the variable ‘KeyVar’ holds the key value. The function returns the value of
the element identified by the key from the simple list variable ‘SLV Emp’.

Retrieving value from Compound List Variable


$$ListValue:CLVEmp:##KeyVar:Age
In this example, the variable ‘KeyVar’ holds the key value. The function returns the identified
Compound List Variable element’s member variable value. In our case, we have specified the
member specification as ‘Age’.

463
Variable Framework

$$ListValueEx
The Function $$ListValueEx returns the value of an element at the specified index in the list.
Syntax
$$ListValueEx : <List Variable Specification>:<Index Formula>+
[:< Member Specification>]
Where,
<List Variable Specification> is the simple or compound list variable specification
<Index Formula> can be an expression which evaluates to an index number
<Member Specification> this specification is required only if the value needs to be extracted
from a specific member of a compound list variable
Example:
Retrieving value from Simple List Variable
$$ListValueEx:SLVEmp:##IndexVar
In this example, the variable ‘IndexVar’ holds the index value. The function returns the value
of the element identified by the index from the simple list variable ‘SLV Emp’.

Retrieving value from Compound List Variable


$$ListValueEx:CLVEmp:##IndexVar:Age
In this example, the variable KeyVar holds the index value. The function returns the identi-
fied Compound List Variable element’s member variable value. In our case, we have specified
the member specification as ‘Age’.

Index Based Retrieval using ## Operator


The operator ## is used to access the value of the variable. This operator is extended to allow
dotted notation syntax to access variables / member variables / element variables of a list at
any level.
When this operator is used on a compound variable (without path specification), it returns the
value of the first member variable by default. Similarly, on a list variable this returns the
number of items in the list.
Syntax
##<Element Variable Specification>.<Member Variable +
Specification>.< Simple Member Value specification>

464
Variable Framework

Where,
<Element Variable Specification> can be a compound variable or compound list variable
[Index Expression]
<Member Variable Specification> can be a compound variable member or compound list
member variable [Index Expression]
<Simple Member Value Specification> refers to the name of the simple member in the
specified path
<Index Expression> can be an expression that evaluates to number. Suffixing a variable with
index refers to an element variable. This can be positive or negative. Negative index denotes
reverse access.
Example:
Retrieving Value from Simple List Variable
SET : TempVar : ##SLVEMP[3]
The value of the element identified by the index ‘3’ from the Simple List Variable ‘SLVEMP’
will be set to the variable ‘TempVar’.

Retrieving Value from Compound List Variable


LOG : ##CLVEmp[2].Relatives[1].Name
In this example, we are retrieving value of the identified Compound List Variable (Relatives)
element’s member variable value. ‘Relatives’ is a member variable of the Compound List
Variable CLVEMP
Looping Construct –For In/For Each
The FOR IN loop is used to iterate over the values in the list variable. The number of iterations
depends on the number items in the list variable.
Syntax
FOR IN : <Iterator Variable>: <List Variable Name >
.
.
END FOR
Where,
<Iterator Variable> is the name of the variable which holds the Key value in every occur-
rence of the iteration.
<List Variable Name> is the name of simple list or compound list variable.
This construct will walk only the elements in the list which are having key. Since, the iterator
variable is filled with a key for each element; all elements which do not have key are ignored.

465
Variable Framework

This is useful to walk keyed list variable elements in the current sorting order. If the element
does not have key then other loops like WHILE, FOR, etc can be used and these elements can
be operated via index.
Example:
Iterating the Simple List Variable Values
FOR IN : KeyVar : SLV Emp
LOG : $$String:$$ListValue:SLVEmp:##KeyVar
END FOR
In this example, the iterator variable KeyVar holds the Key value in every occurrence of the
iteration. In every iteration, the value of the element identified by the key is logged using the
function $$ListValue.

Iterating the Compound List Variable Values


FOR IN : KeyVar : CLV Emp
LOG : $$String:$$ListValue:CLVEmp:##KeyVar:Age
END FOR
In this example, the iterator variable “KeyVar” holds the Key value in every occurrence of the
iteration. In every iteration, the value of member “Age” of the element of the Compound List
Variable “CLVEMP” identified by key is logged using the function $$ListValue.

The looping construct FOR EACH is an alias for the looping construct FOR IN.

List Variable Specific Functions


$$ListKey
The function $$ListKey returns the corresponding key for the given index.
Syntax
$$ListKey: <List Variable Specification>: <Index Specification>

Where,
<List Variable Specification> is the simple list or compound list variable specification
<Index Specification> can be an expression which evaluates to a number.

466
Variable Framework

Example:
Retrieving key from a Simple List Variable
01 : LOG : $$ListKey:SLVEMP:2
In this example, Key of the second element of Simple List Variable ‘SLVEMP’ is retrieved.

Retrieving key from a Compound List Variable


02 : LOG : $$ListKey:CLVEmp[1].Relatives:1

In this example, Key of the first element of Compound List Variable ‘Relatives’ is retrieved.
‘Relatives’ is a member of Compound List Variable ‘CLVEMP’.

$$ListIndex
The function $$ListIndex returns the Corresponding index for the given Key
Syntax
$$ListIndex: <List Variable Specification>: +
<Key Specification>
Where,
<List Variable Specification> is the simple list or compound list variable specification
<Key Specification> can be an expression which evaluates to string value.

Example:
Retrieving index from a Simple List Variable
01 : LOG : $$ListIndex:SVEMP:E001
In this example, the index of the element identified by the key value ‘E001’ is retrieved from
the Simple List Variable ‘SLVEMP’
Retrieving index from a Compound List Variable
02: LOG : $$ListIndex:CLVEmp:E001

In this example, the index value of the element identified by the key value ‘E001’ is retrieved
from the Compound List Variable ‘CLVEMP’.

$$ListCount
The function $$ListCount retrieves the number of items in the list.

467
Variable Framework

Syntax
$$ListCount:<List Variable Specification>
<ListVariable Specification> is the simple list or compound list variable specification
Example:
01 : LOG : $$ListCount:SLVEMP
02 : LOG : $$ListCount:CLVEMP

$$ListFind
This function is used to check if a given key exists in the list or not. It returns a logical flag
indicating the existence of the key.
Syntax
$$ListFind:<List Variable Specification>:<Key Formula>
<List Variable Specification> is the simple list or compound list variable specification
<Key Formula> can be an expression which evaluates to a string value.
Example:
01 : LOG : $$ListFind:SLVEMP :E001
02 : LOG : $$ListFind:CLVEMP:E001

$$ListValueFind
This function can be used to check if a given value exists in the list. If a given list has more
than one same value, index can be used to retrieve the n’th matching value.
Syntax
$$ListValueFind:<List Variable Specification>:+
<Occurance Specification>:<Value Formula>+
[:<Member Specification>]

Where,
<List Variable Specification> is the simple list or compound list variable specification
<Occurance Specification> can be an expression which evaluates to a number
<Value Formula> can be an expression which evaluates to a value
<Member Specification> can be specified if the list element is compound. It is optional
Example:
;; Finding value from the Simple List Variable
01 : LOG : $$ListValueFind:SLVEMP:1:RAMESH

468
Variable Framework

;;Finding value from the Compound List Variable with member specification.
03 : LOG : $$ListValueFind:CLVEmp:1:PRIYA:Name
The function will return Yes if the value exists in the list else it will return No.
Some Common Functions Used
$$IsSysNameVar
This function checks if the variable has a value which is a SysName like Not Applicable, End
of List, etc. In case of repeated variables if any one value is a non-sysname returns FALSE.
Syntax
$$IsSysNameVar:<Variable Specification>
Where,
<Variable Specification> is the simple variable path specification
Example:
$$IsSysNameVar:EmpVar
In this example, the function $$IsSysNameVar returns logical value YES if the variable
EmpVar has sysname as value else it returns NO.

$$IsDefaultVar
This function determines that the content of the variable has a “Default” or blank as the value.
This function is applicable only for simple variables. In case of simple repeated variable, if
any one value is non-default, then this is not a default variable.
Syntax
$$IsDefaultVar:<Variable Specification>

Where,
<Variable Specification> is the simple variable path specification

Example:
[Field: DefaultVar]
Set as : $$IsDefaultVar:SVValuationMethod
In this Example the function $$IsDefaultVar returns logical value YES if value of variable
“SVValuationMethod“ is blank or "Default" else it returns NO.
$$IsActualsVar
This function checks if the content of the variable is blank or sysname or “ACTUALS”.
Syntax
$$IsActualsVar:<Variable Specification>

469
Variable Framework

Where,
<Variable Specification> is the simple variable path specification
Example:
$$IsActualsVar:SVBudget
In this example, the function $$IsActualsVar returns logical value YES if the value of variable
SVBudget is blank or sysname or “ACTUALS” else it returns NO.

$$IsCurrentVar
This function checks if the content of the variable is Blank or Sysname or “Stock in hand”.
Syntax
$$IsCurrentVar : <Variable Specification>
Where,
<Variable Specification> is the simple variable path specification
Example:
$$IsCurrentVar:DSPOrderCombo

In this Example, the function $$IsCurrentVar returns logical value “YES” if value of variable
“DSPOrderCombo“ is blank or sysname or "Stock-In-Hand" else it returns “No”.

$$ExecVar
This function returns the value of a variable in the parent report chain.
Syntax
$$ExecVar:<Variable Specification>
Where,
<Variable Specification> is the simple variable path specification
Example:
$$ExecVar:DSPShowMonthly

In this example, the function $$ExecVar returns the value of the variable DSPShowMonthly
from the parent report.

$$FieldVar
This function returns the value of the field which is acting as a variable with the specified
name.

470
Variable Framework

Syntax
$$FieldVar:<Variable Specification>
Where,
<Variable Specification> is the simple variable path specification

Example:
[Collection: GodownChildOfGodownName]
Type : Godown
Child of : $$FieldVar:DSPGodownName
In this example, $$FieldVar is used to fetch the value of the variable DSPGodownName
whose value is modified in a field. This value becomes the value for the ChildOf attribute.

$$ParentFieldVar
This function gets the field variable value from its parent report.
Syntax
$$ParentFieldVar:<Variable Specification>
Where,
<Variable Specification> is the simple variable path specification

Example:
[Field: ParentFieldVar]
Set as : $$ParentFieldVar:SVStockItem
In the above Example the function returns field variable value from its parent report for the
variable “SVStockItem”

Populating List from a Collection


The action LIST FILL is used to fill a list from a collection instead of using the looping con-
structs. The specified collection is walked and the key formula and value formula is evaluated
in the context of each object to create list elements.
Syntax
LIST FILL : <List Variable Specification> : <CollectionName>+
[:<Key Formula> [:<Value Formula> +
[:<Member Specification>]]]

471
Variable Framework

Where,
<List Variable Specification> is the simple list or compound list variable specification
<Collection Name> is the name of collection from which the values needs to be fetched to fill
the list variable.
<Key Formula> can be an expression which evaluates to string value. It is optional.
<Value Formula> can be an expression which returns a value. The data type of the value must
be same as that of list variable. Value formula is optional if not specified only KEY is set for
each added element
<Member Specification> Member specification can be given if the list contains a compound
variable.

If both key & value are not specified blank elements are added to the list.

Example:
Populating Simple List Variable from a Collection
LIST FILL : SLV Emp : Employees :$Name:$Name
All employee names from the collection ‘Employees’ will be added to the Simple List
Variable once the action LIST Fill is executed.

Populating Compound List Variable from a Collection


LIST FILL : CLV Emp : Employees :$Name:$Name

In this example, all employee names from the collection ‘Employees’ will be added to the first
member variable as there is no member specification.

LIST FILL : CLV Emp : Employees :$Name: $Designation:Designation

In this example, Designations of all employees from the collection ‘Employees’ will be added
the member variable ‘Designation’.
LIST FILL: CLV EMP[1].Relatives:$Name:$SpouseName:Name
In this example, spouse name of all employees from the collection ‘Employees’ will be added
to the member variable ‘Name’ of a Compound List Variable ‘Relatives’. ‘Relatives’ is a
member variable of the Compound List Variable ‘CLVEMP’.

472
Variable Framework

Sorting of List Elements


Initially when the list variable is created, it is sorted on the order of insertion. TDL provides
the facility to sort the values in the list variable either on key or value. Following actions
allows changing the sort order:-
 List Key Sort
 List Value Sort
 List Reset Sort

Action LIST KEY SORT


The action LIST KEY SORT allows the user to sort the elements of the list based on the key.
Keys are by default of type string, so absence of key data type specification will consider key
data type as string while sorting. The user can override this by specifying a key data type.
Keys are optional for elements. All elements in the list may not have a key. In such cases,
comparisons of elements would be done on the insertion order.
Syntax
LIST KEY SORT : <List Variable Specification>[:<Ascending/+
DescendingFlag> [:<Key Datatype>]]
Where,
<List Variable Specification> is the simple list or compound list variable specification
<Ascending/DescendingFlag> can be YES/NO. YES is used to sort the list in ascending
order and NO for descending. If the flag is not specified then the default order is ascending.
<Key Data Type> can be String, Number etc. It’s optional.

The action LIST SORT is an alias for the action LIST KEY SORT.

Example:
Sorting Simple List based on Key
LIST KEY SORT : SLVEmp: Yes : String ;;Ascending order

LIST KEY SORT : SLVEmp: No : String ;;Decending order

Sorting Compound List based on Key


LIST KEY SORT: CLVEmp: Yes : String ;;Ascending order

LIST KEY SORT: CLVEmp[1].Relatives : No : String ;;Decending order

473
Variable Framework

Action LIST VALUE SORT


The action LIST VALUE SORT allows the user to sort the elements of the list based on the
value.
The data are sorted as per the data type specified for the list variable in case of simple list, and
the member specification data type in case of compound list. If a compound list is chosen and
member specification is not specified, then the list is sorted by the value of the first member
variable.
If duplicate values are in the list, the key data type passed is considered to sort by key, and then
in absence of key, insertion order is used.
Syntax
LIST VALUE SORT :<List Variable Specification>+
[:<Ascending/DescendingFlag> [:<Key Datatype>+
[:<Member Specification>]]]

Where,
<List Variable Specification> is the simple list or compound list variable specification
<Ascending/DescendingFlag> can be YES/NO. YES is used sort the list in ascending order
and NO for descending. If the flag is not specified then the default order is ascending.
<Key Data Type> can be string, number etc. It is optional.
<Member Specification> is the member specification incase of compound list. If not
specified then the list is sorted by the value of first member variable.
Example:
Sorting Simple List based on Value

LIST VALUE SORT: SLVEmp: Yes : String ;;Ascending order

LIST VALUE SORT: SLVEmp: No : String ;;Decending order

Sorting Compound List based on Value


LIST VALUE SORT: CLVEmp: Yes : String ;;Ascending order
LIST VALUE SORT: CLVEmp[1].Relatives: No : String ;;Decending order

Action LIST RESET SORT


The action LIST RESET SORT resets the sorting method of the list and brings it back to the
insertion order.

474
Variable Framework

Syntax
LIST RESET SORT: <List Variable Specification>
Where,
<List Variable Specification> is the simple list or compound list variable specification
Example:
LIST RESET SORT: SLVEMP
LIST RESET SORT: CLVEMP

Field Acting as a Variable


The Variable attribute in a Field Definition is used to make the field behave as a variable with
the specified name. The variable need not be defined as it inherits data type from the field
itself. Field can act as simple variable only since it can hold only simple value.
Syntax
[Field : <Field Name>]
Variable : <Variable Name>

Where,
<Field Name> is the name of the field.
<Variable Name> is the name of variable.
Example:
[Field: EmployeeName]
Variable : EmpNameVar
Implication of Repeat Variables in Columnar Report
The report in which the number of columns added or deleted as per the user inputs is referred
to as Columnar Report. In a Columnar Report, Lines are repeated vertically and Fields are
repeated horizontally. The Columnar Report can be a

 MultiColumn Report - Column can be repeated based on the user input


 AutoColumn Report - Multiple columns can be repeated based on the user input
on a single click of a button
 Automatic Auto Columns - Report can be started with predefined multiple columns
without user intervention
Let us see the implications of Repeat Attribute of Variable / Report / Line Definitions in
context of Columnar Reports.

475
Variable Framework

Repeat Attribute of Variable Definition


Please refer to the topic “Variable Definition and Attributes”.
Repeat Attribute of Report Definition
The Repeat Attribute of Report Definition is used specifically in Columnar Reports. When we
specify Repeat attribute with a variable name, the reports becomes a Columnar Report and the
columns are added based on number of values stored in the variable. Only simple variables
can be repeated. Also, a report can have more than one variables repeated. In such cases, the
number of columns in the report depends on the maximum value a Repeat Variable holds.
The Repeat attribute of the report is declaration cum repeat specification, so a separate decla-
ration is not required. Even if a declaration is done using a Variable attribute Repeat is consid-
ered as a repeat specification.
Syntax
[Report: <Report Name>]
Repeat : <Variable Names>
Where,
<Report Name> is the name of the Report
<Variable Names> is the list of comma separated variables
Repeat Attribute of Line Definition
The Repeat Attribute of Line Definition is used to repeat the Field horizontally in columns.
Syntax
[Line: <Line Name>]
Repeat : <Field Name>
Where,
<Line Name> is the name of the line
<Field Name> is the name of the field which needs to be repeated.
Example:
Let us look in to the usage of Repeat Attribute at Variable / Report / Line Definitions in
designing the Columnar Stock Item wise Customer wise Sales Report
In this report, stock item names should be repeated vertically and customer/party names
should be repeated horizontally. The columns should be automatically available when the
report is started.
Repeat Attribute of Variable Definition
[Variable: PName]
Type : String
Repeat : ##DSPRepeatCollection

476
Variable Framework

The variable ‘DSPRepeatCollection’ holds the collection name ‘CFBK Party’. The collection
definition is as below. This collection contains a method name ‘PName’. In this case, the
variable ‘PName’ would be filled with the method value from each object of the collection
“CFBK Party”.

[Collection: CFBK Party]


Source Collection: CFBK Voucher
Walk : Inventory Entries
By : PName : $PartyLedgerName
Aggr Compute : BilledQty : SUM : $BilledQty
Filter : NonEmptyQty
The variable ‘PName’ holds the multiple values based on an implicit index. Method value of
the each object of the collection ‘CFBK Party’ will be picked up and stored in to the variable’s
first index, second index and so on.
Repeat Attribute of Report Definition
[Report: CFBK Rep]
Use : DSP Template
Form : CFBK Rep
Variable : DoSetAutoColumn, PName
Repeat : PName
Set : DoSetAutoColumn : Yes
Set : DSPRepeatCollection : "CFBK Party"
Set : SVFromDate : $$MonthStart:##SVCurrentDate
Set : SVToDate : $$MonthEnd:##SVCurrentDate

The attribute Repeat determines that it is a Columnar Report. The number of columns
depends on the number of values available in the variable PName.

Repeat Attribute of Line Definition


[Line: CFBK Rep Details]
Fields : CFBK Rep Name, CFBK Rep Party, CFBK Rep Col Total
Repeat : CFBK Rep Party
Total : CFBK Rep Party

477
Variable Framework

The Field ‘CFBK Rep Party’ is repeated based on the number of values of variable (Num-
Sets). So those many numbers of instance of the field are created. Each field will have an
implicit index number (starting from 1). This implicit index is used to evaluate expressions in
the context of the field.
Common Functions used with Columnar Reports
$$NumSets
This function returns the number of columns in the report. It does not take any parameter. If
the report is an auto report or sub report, it returns the number of columns in the parent of the
auto/sub report.
Number of set is the maximum number of values a repeated variable can hold in that report.
Syntax
$$NumSets
Example:
[Field: CFBK Rep Col Total]
Use : Qty Primary Field
Set as : $$Total:CFBKRepParty
Border : Thin Left
Invisible: $$Numsets=1

In this example, the total column will be invisible if there is only one column in the report.

$$LowValue
This function can be used to get the lowest value in a set of values in the repeated variable.
Syntax
$$LowValue:<Variable Specification>
Where,
<Variable Specification> is a simple variable specification
Example:
Let us suppose, the Repeat Variables in a Columnar Report are SVFromDate and SVToDate

Consider the below Field Definition in the same report:


[Field: VariableLowValue]
Use : Name Field
Set as : $$LowValue:SVFromDate

478
Variable Framework

The function $$Lowvalue returns the lowest value in a set of values in the repeat variable
SVFromDate

$$HighValue
This function can be used to get the highest value in a set of values in the repeated variable.
Syntax
$$HighValue:<Variable Specification>
Where,
<Variable Specification> is a simple variable specification

Example:
Let us suppose, the Repeat Variables in a Columnar Report are SVFromDate and SVToDate
Consider the below Field Definition in the same report:
[Field: VariableHighValue]
Use : Name Field
Set as : $$HighValue:SVToDate

The function $$HighValue returns the highest value in a set of values in the repeat variable
SVToDate

$$IsCommon
This function is used with repeated variable to check if all the values in the repeat set are same.
Syntax
$$IsCommon:<Variable Specification>
Where,
<Variable Specification> is a simple variable specification
Example:
Let us suppose, the Repeat Variable in a columnar report is SVCurrentCompany
Consider the below Field Definition in the same report

[Field: VariableIsCommon]
Use : Logical Field
Set as : $$IsCommon:SVCurrentCompany

479
Variable Framework

The function $$IsCommon returns a logical value ‘Yes’ if all the values in the SVCurrent-
Company are same otherwise it returns ‘No’

$$VarRangeValue
This function gets a list of variable values separated by specified separator character. If no
separator character is specified, by default comma (,) is taken as separator character.
Syntax
$$VarRangeValue:<Variable Specification>[:<Separator +
Character> [:<Start Position> [:<End Position>]]]
Where,
<Variable Specification> is the simple variable specification
<Separator Character> is the seperator character
<Start Position> is the index which denotes the starting position
<End Position> is the index which denotes the ending position
Specifying start and end positions are optional. If not specified, the function
will return all the values of the specified Repeat Variable separated by
comma(,)

If start and end positions are specified, the function will return the values of repeat variable
with in the specified index range. Again, specifying end position is optional. If end position is
not specified, the function will return the entire values from the starting position.
Example:1
$$VarRangeValue:SVFromDate
In this example, the function returns the entire set of values of the Repeat Variable SVFrom-
Date.
Example: 2
$$VarRangeValue:SVFromDate:",":1:5
In this example, the function returns the value of the specified index range (1 to 5) of the
Repeat Variable SVFromDate
Example:3
$$VarRangeValue:SVFromDate:",":3
In this example, the function returns the entire set of values from the Starting Index position of
the Repeat Variable SVFromDate

480
Variable Framework

Variables usage and behaviour in Auto Report


A report can be marked as an auto report via AUTO attribute; this indicates the system that,
this report cannot instantiate its own variables. These reports inherit variables from the parent
scope. This is mainly used for configuration reports which require modifying the configuration
variables of parent report.
Syntax
[Report: <Report Name>]
Auto : <Logical Value>
Where,
<Report Name> is the name of the report
<Logical Value> can be YES / NO. Default value is No.
Example:
[Report: Voucher Configuration]
Auto : Yes
Title : $$LocaleString:"Voucher Configuration"
The above is a default configuration report which marked as an Auto Report is used to modify
the variables of parent report.
A report can be launched in ‘Auto’ mode through the Actions Modify Variable and Modify
System

Action MODIFY VARIABLE


The action MODFY VARIABLE launches the given report in ‘auto’ mode. Since the launched
report is in auto mode, this cannot have its own instance of variables and any modification
would affect the parent context
Syntax
MODIFY VARIABLE : <Report Name>
Where,
<Report Name> is the name of the report which is to be launched in ‘Auto Mode’
Example:
Let us look in to the below code snippet
[Button: F2 Change Period]
Key : F2
Action : Modify Variables : Change Period
Title : $$LocaleString:"Period"

481
Variable Framework

The Action Modify Variable is launched the report Change Period in Auto Mode. The report is
having two fields SVFromDate and SVToDate
[Field: SVFromDate]
Use : Short Date Field
Modifies : SVFromDate
Variable : SVFromDate

[Field: SVToDate]
Use : Short Date Field
Format : Short Date, End:#SVFromDate
Modifies : SVToDate
Variable : SVToDate

The varible value changes would affect the parent report context only (i.e. It will affect values
of the variables SVFromDate and SVTodate which are associated to the report from which the
report Change Period is launched in Auto Mode)

Action MODIFY SYSTEM


The action MODIFY SYSTEM launches the given report in ‘auto’ mode. Even if this report is
called under some other report context, this action makes the new report to get the system
context and thereby modify system scope variables.
Syntax
MODIFY SYSTEM : <Report Name>
Where,
<Report Name> is the name of the report which is to be launched in ‘Auto Mode’
Let us look in to the default code snippet
[Button: Change System Period]
Key : Alt+F2
Action : Modify System : Change Menu Period
Title : $$LocaleString:"Period"

The Action Modify System has launched the report Change Period in Auto Mode. The report
is having two fields SVFromDate and SVToDate

482
Variable Framework

[Field: SVFromDate]
Use : Short Date Field
Modifies : SVFromDate
Variable : SVFromDate

[Field: SVToDate]
Use : Short Date Field
Format : Short Date, End:#SVFromDate
Modifies : SVToDate
Variable : SVToDate

The value changes would affect the variables at System Scope as the report is launched using
the Action Modify System.

Repeat Line with Optional Collection


Values of the List Variables (Simple/Compound) can be stored / altered by accepting user
inputs and also displayed in a report by repeating a line without a collection. Since variables
are context free structures there is no need to associate element variables with the line. In cases
where collection is not specified then the number of lines to be repeated is unknown. Hence,
specifying SET attribute is mandatory. In case of Edit, SET can be optional if Break on is
specified.
Syntax
[Part: <Part Name>]
Repeat : <Line Name> [: <Collection>]

Where,
<Part Name> is the name of the part
<Line Name> is the name of the line to be repeated
<Collection> is the name of the collection on which the line is repeated. It is optional when a
line is repeated to store / alter /display values of list variable.

Storing Values into List Variables


Values can be added to the List Variable (Simple/Compound) dynamically by accepting the
user inputs by repeating a line without a Collection. Multiple lines can be added dynamically
or fixed number of lines can be added as per user requirement while repeating the line.

483
Variable Framework

Example:
To accept the values from a user to the Simple List Variables SLVEMP, a report is opened in
create mode. Let us look in to the Part Definition
[Part: SLV List Values]
Lines : SLV List Title, SLV List Values
Repeat : SLV List Values
BreakOn : $$IsEmpty:#SLVAlias
Scroll : Vertical
In this example, the line is repeated without a collection and it will break if the fields value
‘SLV Alias ‘is empty.
Let us look in to the Field Definitions
[Line: SLV List Values]
Fields : SLV Alias, SLV Name

[Field: SLV Alias]


Use : Name Field

[Field: SLV Name]


Use : Name Field
Delete : Key
Add : Key : SLV List Key
Inactive : $$IsEmpty:# SLVAlias

[Key: SLV List Key]


Key : Enter
Action List: Field Accept, SLV List Add

[Key: SLV List Add]


Key : Enter
Action : LIST ADD:SLVEMP:#SLVAlias:#SLVName
Values are added to the List Variable “SLVEMP” using the Action “LIST ADD”. Similar
way, user inputs can be added / altered dynamically to the Compound List Variable also.

484
Variable Framework

Retrieving Values from List Variables


In the above example, we had stored the values in to a Simple List Variable “SLVEMP”. Let
us suppose, the values need to be retrieved from the Simple List Variable “SLVEMP” and
displayed in a Report.
This report “SLV List Values with Key Display” is opened in Display mode. Let us look in to
the code snippet of the part definition:-
[Part: SLVList ValuesDisplay]
Lines : SLV List DisplayTitle, SLV List DisplayValues
Repeat : SLV List DisplayValues
Set : $$ListCount:SLVEmp
Scroll : Vertical
CommonBorder : Yes
In part level, the number of lines is fixed using the Attribute ‘SET’ based on the number of
elements in the Simple List Variable “SLVEmp”.

[Line: SLV List DisplayValues]


Fields : SLV Alias, SLV Name

[Field: SLV Alias]


Use : Name Field
Set as : $$ListKey:SLVEMP:$$Line

[Field: SLV Name]


Use : Name Field
Set as : $$ListValue:SLVEMP:#SLVAlias
Key and Value from the Simple List Variable “SLVEMP” are retrieved using the functions
$$ListKey and $$ListValue at the field level.
Similar way, the values can be retrieved from a Compound List Variable also.

Exercise 9.1
Objective
The objective of this program is to understand the concept of List Variable

485
Variable Framework

Capabilities Used
 Attribute “List Variable” at the System Variable definition to declare the Compound
List Variable
 Attribute ‘Repeat’ used at Part definition for repeating line without collection
 Variable Dotted Syntax for setting value to the elements within the Compound List
Variable
 Variable Dotted Syntax with ## prefix to extract values from the elements within the
Compound List Variable
 Functions $$ListIndex and $$ListKey to find out the Key and Index of the Element.
Code
[Report: Exer List Variable]
Form : Exer List Variable
Title : "List Variable"

[Form: Exer List Variable]


Parts : Form SubTitle, Exer List Variable
Width : 50% Page
Local : Field: Form SubTitle: Info: "Usage of List Variable"
On : Form Accept: Yes: Display: Exer LV Display

[Part: Exer List Variable]


Lines : Exer LV Title, Exer LV Details
Repeat : Exer LV Details
Scroll : Vertical

/* Break/Discontinue the repetition if the Field value 'ExerLVStudName' is found empty*/


Break On: $$IsEmpty:#ExerLVStudName

[Line: Exer LV Title]


Fields : Exer LV StudName, Exer LV StudID, Exer LV StudClass
Local : Field: Exer LV StudName: Set As: "Student Name"
Local : Field: Exer LV StudID: Set As: "ID"
Local : Field: Exer LV StudClass: Set As: "Class"
Border : Thin Top Bottom

486
Variable Framework

[Line: Exer LV Details]


Fields : Exer LV StudName, Exer LV StudID, Exer LV StudClass
Local : Field: Exer LV StudName : On: Focus : $$Line > 1: CALL:+
ExerLVUpdate : @PrevStud: @PrevID: @PrevClass

[Field: Exer LV StudName]


Use : Name Field
PrevStud : $$PrevLine:#ExerLVStudName
PrevID : $$PrevLine:#ExerLVStudID
PrevClass : $$PrevLine:#ExerLVStudClass

[Field: Exer LV StudID]


Use : Name Field
Inactive : $$IsEmpty:#ExerLVStudName

[Field: Exer LV StudClass]


Use : Name Field
Inactive : $$IsEmpty:#ExerLVStudName
/* Function to update List Variables*/
[Function: Exer LV Update]
Parameter : pStudent : String
Parameter : pStudID : String
Parameter : pStudClass : String
Variable : IndexFromKey : Number

/*Action 'List Add' adds an element to the Compound List Variable 'Exer LV Student' with a key assigned to it. */
00: LIST ADD: Exer LV Student : ##pStudent
/* Function 'ListIndex' is used to return the index of the Compound List Variable for a specific key */
10: SET : IndexFromKey : $$ListIndex:ExerLVStudent:##pStudent
/* Using Dotted Syntax, setting the value to the elements within the Compound List Variable*/
20: SET : ExerLVStudent[##IndexFromKey].ExerLVStudID:##pStudID
30: SET : ExerLVStudent[##IndexFromKey].ExerLVStudClass:##pStudClass

487
Variable Framework

[Variable: Exer LV Student]


/* Specifying 2 elements within the Compound Variable 'Exer LV Student' */
Variable : Exer LV StudID: String
Variable : Exer LV StudClass: String

[System: Variable]
/* Declaring the Compound Variable 'Exer LV Student' as a System Variable having list of values */
List Variable: Exer LV Student
/* Report to display List Variables */

[Report: Exer LV Display]


Form : Exer LV Display
Title : "List Variable values displayed"

[Form: Exer LV Display]


Parts : Form SubTitle, Exer LV Display
Local : Field: Form SubTitle: Info: "List of Students"
Width : 50% Page

[Part: Exer LV Display]


Lines : Exer LV DisplayTitle, Exer LV Display
Repeat : Exer LV Display
/* Function 'ListCount' returns the total number of Items within the List Variable */
Set : $$ListCount:ExerLVStudent
Scroll : Vertical

[Line: Exer LV DisplayTitle]


Fields : Exer LV StudName, Exer LV StudID, Exer LV StudClass
Local : Field: Exer LV StudName: Set As: "Student Name"
Local : Field: Exer LV StudID: Set As: "ID"
Local : Field: Exer LV StudClass: Set As: "Class"
Border : Thin Top Bottom

488
Variable Framework

[Line: Exer LV Display]


Fields : Exer LV StudName, Exer LV StudID, Exer LV StudClass
Local : Field: Default : Inactive: No
Local : Field: Default : Style : Normal
/* Function 'ListKey' returns the Key from within a compound list variable for the specified index */
Local : Field: Exer LV StudName: Set As: $$ListKey:+
ExerLVStudent:$$Line
/* Using Dotted Notation, elements within the list are extracted using ## prefix */
Local : Field: Exer LV StudID: Set As: ##ExerLVStudent[$$Line]+
.ExerLVStudID
Local : Field: Exer LV StudClass: Set As:+
##ExerLVStudent[$$Line].ExerLVStudClass
;;End-of-File
Output

In this exercise,
 We are accepting the details of students from the user such as Student Name, ID and
Class
 Updating the values in to the list variable
 Retrieving values from the list variable and displaying it to the user.

Variable Definition and Declaration


The Compound Variable Exer LV Student is defined and declared as a list variable at the
System Scope.
Storing Values in to the List Variable

489
Variable Framework

The report Exer List Variable is opened in Alter Mode. The line Exer LV Details is repeated
without the collection in the part Exer List Variable. Repetition of the line will be stopped if
the value of the field Exer LV StudName is empty.
User inputs will be accepted at the field level and the function Exer LV Update will be called
on focusing the line satisfying the condition $$Line > 1. Parameters passed to the function
are Student Name, Student Id and Class (field names which are used to accept the user inputs).
In the function Exer LV Update, elements will be added to the list with Student Name as key
using the function $$ListAdd. Values to the elements will be added through Variable Dotted
Syntax using the element index. The function $$ListIndex is used to find out the element
index.
Retrieving Values from the List Variable

On accepting the form which is used to get the user inputs, the report Exer LV Display will be
displayed to show the List Variable values to the user.
In the part Exer LV Display, the line Exer LV Display is repeated without the collection. The
function $$ListCount returns the number of elements in the list variable which determines the
number of repeated lines using the part attribute Set.
The values from the list variable elements are extracted at the field level using the Variable
Dotted Syntax with ## operator prefix.
Variables in Collection
Inline variables can be declared at the collection level using the attributes Source Var,
Compute Var, Filter Var and Parm Var. The usage of declaring these inline variables at collec-
tion level is explained in the lesson Objects, Collections and Internal Object Structure
under the topic Variables in Collection.

Collection from a Variable


Using the collection attribute “Data Source” variable element(s) are gathered as objects in the
collection and their respective simple member variables are available as methods. Member
List Variables are treated as sub-collections.
Syntax
Data Source : <Type> : <Identity> [:<Encoding>]

490
Variable Framework

Where,
<Type> is the type of data source. File XML, HTTP XML, Report, Parent Report, Variable
<Identity> can be file path / scope key words / variable specification based on the type of data
source
<Encoding> can be ASCII or UNICODE. It is applicable for the data source types File XML
& HTTP XML
Example:
Simple List Variable as Data Source
[Collection: LV List Collection]
Data Source : Variable: SLVEmp
The elements of the Simple List Variable ‘SLVEmp’ will be available as objects in the collec-
tion ‘LV List Collection’
Let us suppose if a Line is repeated over the collection ‘LV List Collection’ and the value can
be retrieved in the field level as shown below:-

[Field: SLVEmp Field]


Use : Name Field
Set as : $SLVEmp

10.2.8 Compound List Variable as Data Source


Syntax
[Collection: CV List Collection]
Data Source: Variable: CLVEmp
The elements of the Compound List Variable CLVEmp will be available as objects in the col-
lection CV List Collection. It is used as a Source Collection in the below Summary Collection

[Collection: CV List SummaryCollection1]


Source Collection: CV List Collection
Walk : Relatives
By : Relation: $Relation
Aggr Compute : MaxAge: Max: $Age
Aggr Compute : MinAge: Min: $Age
Aggr Compute : TotSal: Sum: $Salary

491
Variable Framework

In this example, we are walking to the sub-collection “Relatives” and then performing
grouping and aggregation.

Variables in Remoting
In a Tally.NET Environment where Tally at the remote end sends request to the Tally
Company at the Server, all client requests must contain the dependencies based on which data
is gathered. In other words, any request sent to the server must accompany the values config-
ured at the client to extract data from the server. For e.g., a Collection of Ledgers falling under
user selected group must accompany with the request sent to the server. Hence, the request to
the server must contain the Variable value which signifies the Group name.

Only the configuration information which is relevant to the data fetching from the Server
needs to be sent to the Server and not the ones which are User Interface related like Show
Vertical Balance Sheet, Show Percentages, etc.
When a Collection is sent to the Server, all the dependencies i.e., variable values are enclosed
within the requests automatically.
Consider the following examples
Example:1
[Collection: User Ledger Coll]
Type : Ledger
Child of : ##UserSelectedGroup
While sending this collection to the server, automatically the value for the variable UserSelect-
edGroup is also passed to the server and server responds accordingly.
Example:2
[Collection: Emp Coll]
Type : Cost Centre
Filter : EmpSpouseName

[System: Formula]
EmpSpouseName: $SpouseName= ##CLVEMP[1].Relatives[1].Name

In the above example, variable value of CLVEMP[1].Relatives[1].Name will be enclosed


within the request to the server
In some cases, variable values will not be remoted automatically like Child Of : $$FuncName
which in turn returns variable value through the Function. Such variables need to be remoted

492
Variable Framework

using an adhoc Compute within the collection. This Compute is required to set a manual
dependency on the variable and hence consider this while sending request to Server.
Let us consider the below example:
[Collection: User Ledger Coll]
Type: Ledger
Child of: $$UserFunc

[Function: UserFunc]
00 : RETURN : ##FuncVar

In this example, the function UserFunc returns the value through the variable ‘FuncVar’.
Hence, the variable ‘FuncVar’ need to be remoted using an adhoc Compute like below

[Collection: User Ledger Coll]


Type : Ledger
Child of : $$UserFunc
Compute : FuncVar : ##FuncVar

493
Chapter 11: User Defined Fields,
Validation and Controls

Introduction
In the chapter on Object Manipulation, we have covered the concept creating and updating
Internal Objects and persisting the data/information as per the existing structure of the Object.
When an Object needs to be manipulated with a particular data/information it needs to be
reflected against the predefined storage name associated with it. The storage name is same as
the method name available with the Object.
In real life scenarios, as per business requirements the data storage requirements may not be
limited only to the methods already available within the Objects. The Tally user may require
additional fields on the screen apart from the ones available in the Default Tally. For eg : While
entering a Sales Voucher, the dispatch details should store Vehicle details also. In such scenar-
ios, the need to store or persist additional information as a part of existing Internal Object
becomes mandatory.
TDL provides the capability to store additional information as a part of the existing internal
object hierarchy in the form of User Defined Fields. This chapter will completely focus on
defining and storing User Defined Fields. Later, in the chapter we will also cover Validations
and Control which are the most important requirements to maintain integrity of data especially
when additional functionalities are incorporated apart from the ones provided in default.

11.1 User Defined Fields


We have already seen that whenever the data and information entered in the field needs to be
stored into Internal Objects, the attribute storage of the field specifies the method/storage name
into which the corresponding data is reflected.
When additional information needs to be stored within the existing internal objects and
persisted into the Tally Database, User Defined Fields(UDF) are created.
User Defined Fields have a storage component defined by the user. All the valid datatypes
available in TDL are applicable for UDF’s also. i.e A User defined field can be of data type
such as Strings, Amount, Quantity, Rate, Number, Logical and Date.
For usage and implementation of UDF’s, the following points need to be taken care of :

495
User Defined Fields, Validation & Controls

1. The UDF must be defined i.e. a storage component needs to be defined with a spe-
cific data type. At this point the storage does not have a correlation with an Internal
Object
2. The field associated with the UDF needs to be in the context of a Data Object. If the
data is to be stored in a sub-object in the existing hierarchy of Internal Object, then
the field associated with UDF also needs to be in the same sub-object.

11.1.1 UDF Definition


The UDFs are defined under the definition [System: UDF]. The datatype and index number
must be specified while creating the UDF.

Syntax
[System: UDF]
<Name of UDF> : <Data Type>: <Index Number>
Where,
<Name of UDF> identifies the UDF and ideally it should describe the purpose for which it is
created. This is the storage/method name by which it is referred
<Data Type> Is the DataType of the UDF or the keyword “Aggregate”
<Index Number> is any number in the range from 1 and 59999.

The permissible usage range is given below:


 For External Solutions/Customizations - 1 to 9999 and 20001 to 59999
 For Default TDL/Internal Usage - 10000 to 20000

The index numbers 1 to 29 is already used for default TDL which are as
follows:
1 - 29 of data type String
1 - 3 of data type Date and
1 - 2 of data type Number

Example:
[System: UDF]
MyUDF 1 : String : 1001
MyUDF 2 : Date : 1002

496
User Defined Fields, Validation & Controls

In the example above the UDF MyUDF1 is defined with a String Data Type and MyUDF2 is
defined with a Date DataType.
A UDF does not come into existence till some value is stored into it and is attached at with an
Internal Object. An UDF value can be stored along with an object already existing in the Tally
Database or to a new object being created for a specific Object type. Once the value is stored it
can be accessed and used from the specified level just like an ordinary method.

11.1.2 Storing Values into a UDF


As we understand based on Object association methodologies, an Interface Object always
exists in context of a Data Object at any level in the existing Data Object hierarchy. The place-
holder for any data/information is the field Interface Object. A field is used to enter or display
the values pertaining to a method/storage from a particular level of the data object to which it
is associated.
The attribute Storage of field definition is used to specify the UDF/storage component and
attach it at the data object level to which the field is associated ie the field value is stored in the
context of current object.
Syntax
[Field : <Field Name>]
Storage : <Default Storage /UDF Name>
Where,
<Field Name> is the name of the field whose value is to be stored in the UDF.
<Name of UDF> specifies the UDF/Storage name where the field value needs to be stored.

Example:
[Field: NewField]
Use : NameField
Storage : MyUDF
11.1.3 Retrieving values from a UDF
As we have discussed above, an UDF is attached to an Internal Object at a particular level in
the existing hierarchy structure. Once it is stored it can be accessed in the same way as an
existing internal method.
In the context of current object, the value of an UDF can be access by prefixing the $ to the
UDF name.

Syntax
$<UDF Name>

497
User Defined Fields, Validation & Controls

Example:
[Field: NewField]
Use : NameField
Set As : $MyUDF

11.1.4 UDF Types


UDF’s are created with the primary purpose of storing additional information apart from the
ones available as predefined methods and collection in the existing Object hierarchy. The data
storage requirements vary from storing a single/multiple values of a specific datatype to
multiple composite values of varied datatypes. In view of that, UDFs can be classified as given
below
 Simple UDF
 Complex/Compound/Aggregate UDF

Simple UDF
A simple UDF is used when a single or multiple values of a specific datatype needs to be
stored along with the Object specified. A UDF storing a single value of a specific datatype can
be correlated to a method eg : $closingbalance and a UDF storing multiple values of the same
datatype can be correlated to a simple collection eg name and address collection.

Storing Single Value


When a single value pertaining to the value entered in the field needs to be stored, the field
must exist in context of the data object to which it is associated. Let us consider the example
below to understand the storage and retrieval for the same.
Example:
[Report : CompanyVehicles]
Object : Company
|
|
[Field : CVeh ]
Use : Name Field
Storage : Vehicle
Unique : Yes

498
User Defined Fields, Validation & Controls

[System : UDF]
Vehicle: String: 700

In the example above the Report is in context of the Object “Company”. The field “CVeh” is
also in the context of Report Object at the first level only. So, the storage specification at the
field stores the value into the Single non repeat UDF “Vehicle”. Thereafter, the value thus
stored can be retrieved in a field which is in context of the Company Object using $vehicle.

Storing Multiple Values – “Repeat UDF”


Multiple values can be entered into a field when the line containing it is repeated in the part
over the specified UDF. The storage in the field also specifies the name of the UDF. The
implementation and usage of this UDF is exactly like a Simple collection.

Example:
Let us consider the example below to understand the storage and retrieval for the same
Since the implementation of a Simple UDF storing multiple values is exactly like a Simple
Collection, the repeat attribute of Part definition in this case will be as follows:
Syntax
[Part : <Part Name>]
Repeat : <Line name > : <Name of UDF>
Where,
<Part Name> is the name of the part.
<Line Name > is the name of line to be repeated.
<Name of UDF> is the name of the UDF to storing multiple values.

Example:
[Part: CompVeh]
Line : CompVeh
Repeat : CompVeh : Vehicle
Break On : $$IsEmpty:$Vehicle
Scroll : Vertical

[Line : CompVeh]
Field : CVeh

499
User Defined Fields, Validation & Controls

[Field : CVeh]
Use: Name Field
Storage: Vehicle
In the example the line containing the field CVeh is repeated over the Simple UDF Vehicle.
The data entry is repeated till the user enters an empty value. All the values entered are stored
in the UDF Vehicle and are attached to the Company Object associated to the Report. Thereaf-
ter the values stored in the UDF can be retrieved by using $vehicle in the field contained in the
line repeated over the UDF Vehicle.

Aggregate UDF
A Simple UDF can store single or multiple values of a specific datatype i. e it contains single
or repeated values of the same data type.
In real life business scenarios, this does not suffice the data storage requirements. In order to
store composite values of discrete datatypes repeating itself once or multiple times, Aggregate
UDF can be used. An aggregate UDF can contain multiple Simple UDF’s of different
datatypes where the Simple UDF can either be Single or Repeat. It can also contain other
aggregate UDFs within it and this nesting can continue upto infinity. This can be correlated
with Compound Collections.

Aggregate UDF – Definition


Aggregate UDF’s are defined in the same way as Simple UDFs inside the System :UDF defi-
nition. The datatype to be specified here is “aggregate”. The UDF defined using the keyword
“Aggregate” is actually the container for the subcomponents defined thereafter. The subcom-
ponents can be a Simple UDF or another aggregate UDF.
Syntax
[System: UDF]
Name of aggr UDF : Aggregate : <Index Number>
Component UDF 1 : DataType : <Index Number>
Component UDF 2 : DataType : <Index Number>
|
|
Component Aggr UDF: Aggregate : <Index Number>
Where
<Name of aggr UDF> identifies the UDF and ideally it should describe the purpose for which
it is created.

500
User Defined Fields, Validation & Controls

<Index Number> is any number falling between 1 and 59999. The number falling between 1
to 9999 and 20001 to 59999 can be used for customisation.
<Component UDF> 1-N are the components of the aggregate UDF which are Simple or
aggregate UDFs.

Example:
A company wants to create and store multiple details of company vehicles. The details
required are: Vehicle Number, Brand, Year of Mfg., Purchase Cost, Type of Vehicle, Currently
in Service, Sold On date and Sold for Amount.
To store the required details the sub component simple UDFs are defined and to store that as
one entity one UDF of type Aggregate is defined as shown:

[System : UDF]
Company Vehicles : Aggregate : 1000
VVehicle Number : String : 1000
VBrand : String : 1001
VYear of Mfg : Number : 1000
VPurchase Cost : Amount : 1000
VType of Vehicle : String : 1002
VCurrently in Service : Logical : 1000
VSold On date : Date : 1000
VSold for : Amount : 1001

Storing Values – Aggregate UDF


Multiple values of discrete data types can be entered in different fields contained in a line. This
line will be repeated over the aggregate UDF and the storages in the fields specifies the
component UDF’s.

Aggregate UDF definition does not associate each component field with the aggregate UDF.
The association will take place only when the Line is repeated over aggregate UDF and the
fields within that stores value into the component UDFs.
Since the implementation of Aggregate UDF is exactly like a Compound Collection, the
repeat attribute of Part definition in this case will be as follows:
Syntax
Repeat : <Line name> : <Name of Aggregate UDF>

501
User Defined Fields, Validation & Controls

Where,
<Line Name > is the name of line to be repeated.
<Name of Aggregate UDF> is the name of UDF defined with Aggregate data type.
Example:
[Part : Comp Vehicle]
Line : Comp VehLn
Repeat : Comp VehLn : Company Vehicles
BreakOn : $$IsEmpty:$VBrand
|
|
[Field: CMP VBrand]
Use : Short Name Field
Storage : VBrand

[Field: CMP VVchNo]


Use : Short Name Field
Storage : VVehicleNumber
|In the example the line containing the field ”CmpVBrand” and “CmpVVchNo” is repeated
over the aggregate UDF “Company Vehicles”. The data entry is repeated till the user enters an
empty value in the field “CmpVBrand”. All the values entered in the fields are stored into the
corresponding component UDFs of the aggregate UDF “Company Vehicles” and are attached
to the Company Object associated to the Report. Thereafter the values stored in the individual
UDF’s can be retrieved by using $VBrand, $VVehicleNumber etc in the fields contained in the
line repeated over the aggregate UDF “Company Vehicles”.
Using Sub – Form for User Input
Subform is an attribute that is used with a Field definition to invoke an intermediate report for
accepting user inputs. It relates to a report (not Form). This attribute is useful to activate a
report within a report, perform necessary action and return to the calling report There is no
limit on the number of Subforms that can be used at the field level.
Syntax
[Field: <Field Name>]
Sub Form : <Report Name> : <Condition>
Where,
<Report Name> is the name of report to be displayed.

502
User Defined Fields, Validation & Controls

<Condition> is any expression, which evaluates to a logical value. When the condition is true
then only the report will be displayed.
A sub form is not associated to the object at the report level. It inherits the object context from
the field which invokes it.

Example:
While entering the Voucher, a subform will be invoked from the field “ACLSLed” which is
used to accept the ledger name. The subform will be invoked only when the ledger name
selected is “Bill Collection” and the Voucher Type is “Receipt”. The subform is used to accept
the relevant details of the customers.

[#Field: ACLSLed]
Sub Form : BillDetail : ##SVVoucherType = "Receipt" +
AND $LedgerName = "Bill Collection"

The report “BillDetail” for the subform uses a Aggregate UDF to store the data. The UDF is
defined as follows:
[System : UDF]
CustName : String : 1000
BillNo : String : 1001
BillAmt : Amount : 1001
FPrint1 : String : 1002
BAggre : Aggregate : 1000

At Part level the line is repeated over the Aggregate UDF.


[Part : BillDetails]
Scroll : Vertical
Line : BillDetailsH, BillDetailsD
Repeat : BillDetailsD : BAggre
Break After : $$Line=2
In the fields Storage attribute is used for all the fields.
[Field : CustName1]
Use : Name Field
Storage : CustName

503
User Defined Fields, Validation & Controls

The aggregate UDF thus stored is attached to the Ledger Entries Object of the specific
Voucher. The Report Bill Details inherits the object context from the field ACLLed which is
associated at the Ledger Entries level of the object Voucher.

Usage – As a Table
The data stored in the Repeat UDF’s and Aggregate UDF’s are analogous to the Objects in the
Collection. This data can be displayed as a table. In order to use the data stored in the UDFs as
a table a collection needs to be constructed.
Collection using UDF stored at the Primary Object level
Since, the UDF will always be attached to an existing internal object, the type specification
will contain reference to the primary object.

Syntax
[Collection: <Collection Name>]
Type : <UDF Name> : <Primary Object Name>
Child Of : Object Identifier
Format : $<UDF Name>, 20

Example:
[Collection: CMP Vehicles]
Type : Vehicle : Company
Childof : ##SVCurrentCompany
Format : $Vehicle, 20
Title : "Company Vehicles"
We have seen in previous examples that the Repeat UDF “Vehicle” stores multiple values of
the same datatype and is associated with the Company Object. The collection “CMP Vehicles”
is constructed by specifying the type as “Vehicle” of a Company Object. The Child of
specifies the Company Object identifier which is the current company.
Once the collection is defined it can be used in the Table attribute of field definition. So when
the cursor is in the defined field the values stored in the UDF will be displayed as popup table.
[Field: EI Vehicles Det]
Use : Short Name Field
Table : CMP Vehicles, Not Applicable
Show Table : Always

504
User Defined Fields, Validation & Controls

Collection using UDF stored at any level in the Object hierarchy


As we know a UDF can be stored at any level in the existing Object hierarchy. In those cases,
referring to the UDF data and construction of the collection using the referencing method as
above is not possible. In those cases the data corresponding to the UDF’s can be gathered only
by traversing to the desired level in the hierarchy. The Walk attribute of the collection will be
used for the same.

Example:
Refer to the example used in using Subforms where the aggregate UDF “BAggr” with compo-
nents BillNo, BillAmt etc is attached at the Ledger Entries level. The source collection is con-
structed using Vouchers of type “Receipt”
[Collection :Src Bills]
Type : Vouchers : Voucher Type
Child Of : $$VchTypeReceipt
The BillTable collection walks over the Ledger Entries and then over BAggr UDF and then
fetches the methods “BillNo” and “BillAmt”. Format is specified for the methods to be
displayed in the Table.
[Collection : BillTable]
Source Collection : SrcBills
Walk : LedgerEntries, BAggr
Fetch : BillNo, BillAmt
Format : $BillNo, 10
Format : $BillAmt, 20

The above table is attached to the field “VchNarration”


[#Field : VchNarration]
Table : BillTable

Exercise 11.1
Objective
The objective of this program is to understand the usage and implementation of the User
Defined Fields.

505
User Defined Fields, Validation & Controls

Capabilities Used
 Simple and Aggregate UDF. Aggregate UDF is used to store multiple values.
 The field attribute Storage is used to store the value in the UDF in the current object
context.
 The field attribute Subform is used to display a form from the field.

Code
[Report: Exer User Defined Fields]
Form : Exer User Defined Fields
;; Object Company is associated so any Method or UDF stored will be stored as a part of Company Object and same can
;; be retrieved from Company Object whenever required
Object : Company
Title : "User Defined Fields"

[Form: Exer User Defined Fields]


Parts : Form SubTitle, Exer User Defined Fields
Local : Field : Form SubTitle : Info : "Usage of User Defined Fields"
Width : 40% Page

[Part : Exer User Defined Fields]


Lines : Exer User Defined Fields

[Line : Exer User Defined Fields]


Fields : Long Prompt, Exer User Defined Fields
Local : Field : Long Prompt : Set As : "Enable Company Vehicles +
Module ?"
[Field: Exer User Defined Fields]
Use : Logical Field
;; Field Attribute 'Storage' stores the UDF or Method within the object in context 'Exer Enable Company Vehicles' is an
;; User Defined Field declared under System UDF
Storage: Exer Enable Company Vehicles
;; When the Field Value is Yes, a Sub Form i.e., another Report will be opened
Sub Form: Exer Company Vehicle Details : $$Value = Yes
;; Defining Sub Form

506
User Defined Fields, Validation & Controls

[Report : Exer Company Vehicle Details]


Form : Exer Company Vehicle Details
Title : "Aggregate UDF"
;; Required for Display Report
Object : Company : ##SVCurrentCompany

[Form: Exer Company Vehicle Details]


Parts : Form SubTitle, Exer Company Vehicle Details
Local : Field: Form SubTitle : Info : "Update Company Vehicle +
Details in Aggregate UDF"
[Part: Exer Company Vehicle Details]
Lines: Exer Company Vehicles Title, Exer Company Vehicles Details
;; 'Exer Company Vehicles' is an aggregate UDF and all the independent UDFs are attached together by repeating over
;; aggregate UDF here.
Repeat : Exer Company Vehicles Details: Exer Company Vehicles
Scroll : Vertical
CommonBorder : Yes
;; The Loop will be terminated on encountering empty value for UDF 'ExerVBrand'
BreakOn : $$IsEmpty:$ExerVBrand

[Line: Exer Company Vehicles Title]


Use : Exer Company Vehicles Details
Local: Field: Default: Style : Small Bold
Local: Field: Default: Skip : Yes
Local: Field: Default: Type : String
Local: Field: Default: Delete: Storage
Local: Field: Default: Lines : 0
Local: Field: Default: Delete: Inactive
Local: Field: Default: Align : Center
Local: Field: Exer CMP VBrand : Set as : "Brand"
Local: Field: Exer CMP VCompany : Set as : "Make"
Local: Field: Exer CMP VVehicle Number: Set as : "Number"
Local: Field: Exer CMP VYear of Mfg : Set as: "Year of Purchase”
Local: Field: Exer CMP VPurchase Cost : Set as: "Purchase Cost"

507
User Defined Fields, Validation & Controls

Local: Field: Exer CMP VType of Vehicle: Set as: "Type"


Local: Field: Exer CMP VCurrently in Service: Set as: +
"In Service?"
Local: Field: Exer CMP VSold On Date : Set as: "Sold On"
Local: Field: Exer CMP VSold for : Set as: "For "
Local: Field: Exer CMP VSold On Date : Inactive: No
Local: Field: Exer CMP VSold for : Inactive: No
Border : Thin Top Bottom

[Line: Exer Company Vehicles Details]


Fields : Exer CMP VBrand, Exer CMP VCompany,
Fields : Exer CMP VVehicle Number
Right Fields : Exer CMP VYear of Mfg, Exer CMP VPurchase Cost
Right Fields : Exer CMP VType of Vehicle,
Right Fields : Exer CMP VCurrently in Service
Right Fields : Exer CMP VSold On date, Exer CMP VSold for
Local : Field : Default: Style : Small Bold
Local : Field : Default: Inactive: $$IsEmpty:$ExerVBrand
Local : Field : Exer CMP VBrand: Inactive: No
Local : Field : Exer CMP VSold On Date : Inactive : +
$ExerVCurrentlyInService or $$IsEmpty:$ExerVBrand
Local : Field : Exer CMP VSold for : Inactive : +
$ExerVCurrentlyInService or $$IsEmpty:$ExerVBrand

[Field: Exer CMP VBrand]


Use : Short Name Field
;; UDF 'Exer VBrand' stores the value for Brand within Aggregate UDF 'Exer Company Vehicles'
Storage : Exer VBrand
Border : Thin Left

[Field: Exer CMP VCompany]


Use : Name Field
Storage : Exer VCompany
Border : Thin Left

508
User Defined Fields, Validation & Controls

Table : Exer CMP Veh Company


Show Table : Always

[Field: Exer CMP VVehicle Number]


Use : Name Field
Storage : Exer VVehicleNumber
Border : Thin Left
FullWidth : Yes

[Field: Exer CMP VYear of Mfg]


Use : Number Field
Storage : Exer VYearOfMfg
Border : Thin Left
Format : "No Comma"

[Field: Exer CMP VPurchase Cost]


Use : Amount Field
Storage : Exer VPurchaseCost
Border : Thin Left

[Field: Exer CMP VType of Vehicle]


Use : Short name Field
Storage : Exer VTypeOfVehicle
Border : Thin Left
Table : Exer CMP TypeofVeh
Show Table : Always

[Field: Exer CMP VCurrently in Service]


Use : Logical Field
Storage : Exer VCurrentlyInService
Border : Thin Left
Width : 7

509
User Defined Fields, Validation & Controls

[Field: Exer CMP VSold On Date]


Use : Short Date Field
Storage : Exer VSoldOnDate
Border : Thin Left

[Field: Exer CMP VSold for]


Use : Amount Field
Storage : Exer VSoldFor
Border : Thin Left

[Table: Exer CMP VehCompany]


List Name : "Maruti Suzuki", "Hyundai", "Ford", "TVS", "Bajaj", +
"Hero Honda", "Honda"
Title : "Automobile Companies"

[Table: Exer CMP TypeofVeh]


List Name : "Car", "Van", "Scooter", "Motor Bike", "Truck"
Title : "Type"

[System: UDF]
;; All the UDFs are defined here with Data Type and the Index
Exer Company Vehicles : Aggregate : 1000
Exer Enable Company Vehicles : Logical : 1000
Exer VCurrently in Service : Logical : 1001
Exer VBrand : String : 1000
Exer VCompany : String : 1001
Exer VVehicle Number : String : 1002
Exer VType of Vehicle : String : 1003
Exer VYear of Mfg : Number : 1000
Exer VPurchase Cost : Amount : 1000
Exer VSold for : Amount : 1001
Exer VSold On Date : Date : 1000
;;End-of-File

510
User Defined Fields, Validation & Controls

Output

511
User Defined Fields, Validation & Controls

Program Explanation
The report displayed, prompts the user to Enable the Company Vehicles Module. When the
user enables the module, a report is displayed to accept the vehicle details like Model, Brand,
Date of purchase etc. The attribute Subform is used to display the report for entering vehicle
details.
In the report Exer Company Vehicle Details, line Exer Company Vehicles Details is
repeated over the aggregate UDF Exer Company Vehicles. At the field level, the attribute
Storage is used to save values entered by the user in to the UDF of appropriate data type. The
values are saved in the context of Company object which is associated at Report level. The
Break On attribute of Part is used to specify the termination condition to exit the sub form.
The field attribute Table is used to display the popup for the names of Vehicle Manufacturing
Company and Type of Vehicle. The table contains hardcoded values specified using the Table
attribute List Name.
The UDFs are defined under the definition System:UDF and their data type and index number
is also specified.
11.2 Validation and Controls
The validation can be applied at both Platform as well as TDL level. Platform always enforces
core database integrity constraints. For example a Voucher cannot be saved unless Debit and
Credit amount is matched. Second level validations can be done at the TDL level. This can be
well utilized by the application developers to enforce business requirements.
The Validation concept can be used for different purposes like
 Each business will have unique organizational structure. Naturally this needs to be
reflected in the usage of Tally application. For example the restricting access of
Reports to the Data Entry Person or restricting Data Entry person to create Masters.
 To assist the Data Entry operator to enter meaningful information. For Example PF
Date of Joining should not be less than Date of Joining.
 To enforce the integrity constraints. For example Vouchers having manual number-
ing with ‘prevent duplicates’, duplication of Voucher numbers are not allowed.
 Customized Reports can be brought under default security control

The following section discusses about developing TDL level validation with the help of Defi-
nitions, attributes and built-in functions.

11.2.1 Field Level Attribute


Validate
This attribute checks if the given condition is satisfied. Unless the given condition is satisfied,
the user cannot move further. In other words, if the given condition for Validate is not satis-

512
User Defined Fields, Validation & Controls

fied, the cursor remains placed on the current field without moving to the subsequent field. It
does not display any error message.

Syntax
Validate : <Logical Formula>
Where,
<Logical Formula> returns True/False based on which the cursor movement is decided.

Example:
[Field: CMP Name]
Use : Name Field
Validate : NOT $$IsEmpty:$$Value
Storage : Name
Style : Large Bold
In the above code snippet:
 The field CMP Name is a field in Default TDL which is used to create/ alter a Com-
pany.
 Validate stops the cursor from moving forward, unless some value is entered in the
current field.
 The function, IsEmpty returns a logical value as True, only if the parameter passed to
it contains NULL.
 The function, Value returns the value entered in the current field.

Thus, the Attribute Validate used in the current field, controls the user from leaving the field
blank and forces a user input.

Unique
This attribute takes a logical value. If it is set to Yes, then the values keyed in the field have to
be unique. If the entries are duplicated, an error message, Duplicate Entry pops up. This
attribute is useful when a Line is repeated over UDF/Collection, in order to avoid a repetition
of values.
Syntax
Unique: [Yes / No]

513
User Defined Fields, Validation & Controls

Example:
[!Field: VCHPHYSStockItem]
Table : Unique Stock Item : $$Line = 1
Table : Unique Stock Item, EndofList
Unique : Yes

In this code snippet, the field, VCHPHYSStockItem is an optional field in DefTDL which is
used in a Physical Stock Voucher. The attribute, Unique avoids the repetition of Stock Item
names.

Notify
This attribute is similar to the attribute Validate. The only difference is that it flashes a warning
message and the cursor moves to the subsequent field. A System Formula is added to display
the warning message.

Syntax
Notify : <System Formula> : <Logical Condition>
Where,
<String Formula> is the name of the System Formula which is used to display as message in
message box
<Logical Formula> returns True/False based on this condition message box will trigger
Example:
[!Field: VCH NrmlBilledQty]
Notify : NegativeStock : ##VCFGNegativeStock AND +
@@IsOutwardType AND$$InCreateMode AND +
$$IsNegative:@@FinalStockTotal

In this code snippet, VCH NrmlBilledQty is a default optional field in DefTDL used in a
Voucher. The Notify attribute pops up as a warning message, if the entered quantity for a stock
item is more than the available stock and the cursor moves to the subsequent field.

Control
The attribute Control is similar to Notify. The only difference is that it does not allow the user
to proceed further after displaying a message. The cursor does not move to the subsequent
field.

514
User Defined Fields, Validation & Controls

Syntax
Control : <System Formula> : <Logical Condition>
Where
<String Formula> is the name of the System Formula which is used to display as message in
message box
<Logical Formula> returns True/False based on this condition message box will trigger

Example:
[Field: Employee PFDateOfJoining]
Use : Uni Date Field
Set as : If $$IsEmpty:$PFAccountNumber AND $$IsEmpty:+
$FPFAccountNumber Then "" Else If NOT +
$$FieldEdited OR $$IsEmpty:$PFJoiningDate+
Then $DateofJoin Else $$Value
Storage : PFJoiningDate
Width : 20
Align : Left
Style : Small Bold
Control : PFJoiningDateBelowJoinDate: +
If $$IsEmpty:$PFAccountNumber AND +
$$IsEmpty:$FPFAccountNumber Then No +
Else $$Value < #EmployeeDateOfJoin
Set Always: Yes

In this code snippet, the field, ‘Employee PFDateOfJoining’ is a default field. The control
always makes sure that Date of Joining for a Employee is always less than the Date Provident
Fund joining Date.
The difference between the field Attributes, Validate, Notify and Control are:
Field Attributes Displays Message Cursor Movement
Validate No Restricted
Notify Yes Not Restricted
Control Yes Restricted

515
User Defined Fields, Validation & Controls

11.2.2 Form Level Attribute


Control
When the contents of a Form needs to be validated before accepting them, then Form level
validation can be applied by using attribute Control. This attribute achieves a higher level of
control on the contents of a Form over other controls used at the Lower levels of the Form. If
the condition specified with Control is not satisfied, then the Form displays an error message
while trying to save. The Form cannot be saved until the condition in the attribute Control is
fulfilled.
Syntax
Control: <String Formula> : <Logical Formula>
Where
<String Formula> is the name of the System Formula which is used to display as message in
message box
<Logical Formula> returns True/False based on this condition message box will trigger.

Example:
[Form: Voucher]
Control : DateBelowBooksFrom :$Date < +
$BooksFrom:Company:##SVCurrentCompany
Control : DateBelowFromDate : $Date < $$SystemPeriodFrom
Control : DateBeyondToDate : $Date > $$SystemPeriodTo

In the example, Voucher is a default Form. While creating a voucher, the attribute, Control
does not accept dates beyond the financial period or before beginning of the books.

11.2.3 Menu Level Attribute


Control
The attribute, Control restricts the appearance of Menu Items, based on the given condition.

Syntax
Control: <Key Item Name> : <Logical condition>
Where,
<Key Item Name> is a string represents the Label of the Key Item
<Logical condition> returns True/False based this appearance of Menu Item is decided.

516
User Defined Fields, Validation & Controls

Example:
[Menu: Quick Setup]

Key Item: @@locExciseForManufacturer: M:Display: ExciseMfgr +


QuickSetUp
Control : @@locExciseForManufacturer: @@IsIndian AND +
$$IsInventoryOn
In this code snippet, the Menu, Quick Setup is a default definition. The Menu Item, Excise for
Manufacturer, will be displayed only if the selected company is having statutory compliance
for India Inventory module enabled.
Example:
[Menu: Quick Setup]
Key Item : @@locExciseForManufacturer: M : +
Display : ExciseMfgr QuickSetUp : @@IsIndian AND NOT +
$$IsEmpty:$$SelectedCmps
In this code snippet, the Menu, Quick Setup is a default definition. The Menu Item, Excise for
Manufacturer, will be displayed only if the selected company is having statutory compliance
for India Inventory module enabled else it will be disabled. The disabled Menu Items are
displayed as Greyed- Out and will be Inactive.

11.2.4 Report Level Attribute


Family
The report level attribute Family is useful when the Security Control is enabled for the
company. A Report can be made accessible for only a set of user(s) by setting proper rights at
security levels. For this name of the Report needs to be brought under default Collection
‘Report List’. The value specified with the attribute, Family is automatically added to the
security list as a pop-up while assigning the rights under Security Control Menu.

Syntax
[Report: <Report Name>]
Family : <String Value>
Where,
<String Value> is a string which will appear under Security Control

517
User Defined Fields, Validation & Controls

Example:
[Report:Balance Sheet]
Family : $$Translate:"Balance Sheet"
In this code snippet, the Balance Sheet is added to the Security list. The users having rights to
display Balance sheet can only view the Report.

Function - $$Allow
This built-in function checks the permissions for the currently logged in user. This function
can be effectively used to enable or disable an interface based on the permissions for the
currently logged in user.

Syntax
$$Allow:<Literal Value1>:< Literal Value2>
Where,
<Literal Value1> is a string which decides the type of access.
<Literal Value2> is a string an is the name of Report which pops under default collection
‘Report List’.

Example:
[!Menu: Gateway of Tally]
Key Item : @@locAccountsInfo : A : Menu : Accounts Info. : +
NOT $$IsEmpty:$$SelectedCmps
Control : @@locAccountsInfo : $$Allow:Create:AccountsMasters +
OR $$Allow:Alter:AccountsMasters OR +
$$Allow:Display:AccountsMasters
In this code snippet, the Menu, ‘Gateway of Tally’ is a default optional menu. The Menu Item
‘Account Info.’ will be displayed only if the given condition is satisfied. The function ‘Allow’
checks whether the current user has the rights to access the report displayed under the current
Menu item. The value ‘Accounts Masters’ has been derived from the attribute Family at the
report definition.

Exercise 11.2:
Objective
The objective of this program is demonstrating the usage of various controls at the field level.

518
User Defined Fields, Validation & Controls

Capabilities Used
 The field attributes Notify, Control and Validate are used.
Code
[Report: Exer Field Controls]
Form : Exer Field Controls
Title : "Field Controls"

[Form: Exer Field Controls]


Parts : Form SubTitle, Exer Field Controls
Local : Field: Form SubTitle: Info: "Controls at Field Definition"
Width : 50% Page

[Part: Exer Field Controls]


Lines : Exer Field Notify, Exer Field Control, Exer Field Validate
Local : Field : Long Prompt : Width : 40

[Line: Exer Field Notify]


Fields: Long Prompt, Number Field
Local : Field: Long Prompt: Info: "Enter any Number greater +
than 10 (Notify) :"
;; Field Attribute 'Notify' displays a Warning Message '"Number should be \n greater than 10"' if value entered by the
;; user is less than 10 This will allow the user to continue with a Warning
Local : Field: Number Field: Notify: Number less than 10: +
$$Value < 10

[Line: Exer Field Control]


Fields: Long Prompt, Number Field
Local: Field: Long Prompt: Info: "Enter any Number less than 10+
(Control) :"
/* Field Attribute 'Control' displays an Error Message '"Number should be \n less than 10"' if value entered by the user
is greater than 10 This does not allow user to continue until the condition is satisfied */
Local: Field: Number Field: Control: Number greater than 10 :+
$$Value > 10

519
User Defined Fields, Validation & Controls

[Line: Exer Field Validate]


Fields: Long Prompt, Number Field
Local: Field: Long Prompt: Info: "Enter a Number between 10 to +
20 (Validate) :"
;; Field Attribute 'Validate' does not display any warning or error message but does not allow the user to continue further
;; until the given condition is satisfied
Local: Field: Number Field: Validate: $$Value >= 10 AND+
$$Value <= 20
[System: Formula]
Number less than 10 : "Number should be \n greater than 10"
Number greater than 10 : "Number should be \n less than 10"
;;End-of-file

Output

520
User Defined Fields, Validation & Controls

521
User Defined Fields, Validation & Controls

Program Explanation
The Report Exer Field Controls displays the fields and for each field a control is added. The
field attributes Notify, Control and Validate are used in fields for specifying the behavior when
the given condition is not satisfied.
In the first field the field attribute Notify is used to display the warning message Number
should be greater than 10 as shown in the first image. The Notify attribute displays the
warning message and allows the user to continue.
The second field uses the attribute Control to restrict the value entered in the field. If the
number entered is greater than 10 then it displays the error message “Number should be less
than 10" as shown in the second image. The Control attribute displays the error message and
won’t allow the user to continue until the number entered is less than 10.
The last field uses the attribute Validate to restrict the value entered in the field. If the number
entered is not in the range 10-20 then it won’t allow the user to continue until the number
entered is in between 10 and 20as shown in the third image. The attribute Validate won’t
display any warning/error message.

522
Chapter 12: Advanced Reporting and
Printing

Till now we have concentrated on the language capabilities from the perspective of understand-
ing the interface design elements, internal data object structure, data entry aspects, data storage
and alteration etc.
This is the conclusive chapter of our book and will focus primarily on the output rendering
capabilities. We will examine the Display and Print mode specifically in this chapter. The
initial sections will begin with a discussion on the design of the various Report Layouts and
data retrieval within it. The various printing techniques will be taken up in the subsequent
section.
12.1 Advanced Reporting
Reports are management tools. Their main purpose is to quickly grasp the essential elements
and relationships found in raw data. A business may require a Report for multiple purposes
like:
 To satisfy statutory requirement
 To know the health of the business
 To know the inventory status
 To generate a MIS Report
 To print transaction documents like Invoice, Purchase Order etc.
Default Tally application have number of Accounting, Inventory, Payroll and statutory Reports
which is generated based on the vouchers till date. All the statutory requirements are com-
pletely handled by the default product. But a business may have a specific requirement in the
area of Accounting, Inventory and Payroll. This may lead to make amendments to the existing
default Reports or adding a new report(s).

12.1.1 Tabular Reports


A Tabular Report is the simplest format of all the Report formats. The data is represented as a
series of columns and rows. In a Tabular Report, the number of columns is fixed and is interac-
tive, So that an end user can change the appearance of the Report according to their require-

523
Advanced Reporting and Printing

ment and logically navigate to other Reports. The Day Book, Stock Summary, Trial Balance,
Group Summary are the some of the default Tabular Reports in Tally.ERP 9.

A Tabular Report has the simplest format of all the Report formats. A typical Tabular Report
will have following components:
 Report Title : It contains the Name of the Report, the Title for each column, the
Day/Period for which a Report is generated, etc
 Report Details: It contains the actual information and this Line will be repeated
over the objects of a Collection.
 Report Total: This component is optional and contains the Total of the respective
columns.
A Tabular Report can be made Interactive by adding the following features:
 Adding Button/Key to change the period, to control the appearance of few columns
of the Report, etc
 Adding explosions to the lines
 Drill down to view detailed information about a particular Row (Hierarchical
Reports)

Designing a Tabular Report


A simple tabular report can be designed with following TDL language capabilities:

Part Attributes – Repeat & Scroll


Repeat is used to display the various objects of the collection in the Detail Section of the
report. Repeat attribute repeats the same line over each object of the collection specified.
Scroll is used along with Repeat in order to specify whether the repeated lines will be accom-
modated in the part within the given height or scrolling will be enabled for the part.
Syntax
Repeat : <Line Name> : <Collection Name>
Where,
<Line Name> is the name of the Line which will be repeated multiple times as that of total
number of objects in the Collection given by <Collection Name>
Syntax
Scroll: <Const. Value>
Where,
<Const. Value> can be either Both, Flow or Vertical. In case of Tabular Report the value
Vertical is used have vertical scroll bar for detail Part.

524
Advanced Reporting and Printing

Part attributes – Total & Function $$Total inside a field


The totals pertaining to various columns/fields need to be calculated and displayed within the
Total Line. This is achieved by using Total attribute at the Part level which specifies the
column/field names for which totals are to be calculated. The field which displays the total
uses $$Total to display the calculated value.

Syntax
Total : <Fld1> [,<Fld2>, …]
Where,
<Fld1> is the name of the Field/Column whose running Total will be calculated at Field by
using Built-in Function $$Total
The Built-In function $$Total is used to calculate the running total for all the visible Fields of
a Column
Syntax
$$Total :<Fld1>
Where,
<Fld1> is the name of the Field which is mentioned under the Part definition under Total
attribute.

Example:
In the code snippet given below the part TB Part contains the Title Line TB Title, Detail line
TB Details and the total line TB Totals. The total attribute specifies the field name TB Amount
Field within the detail line. The total line TB Total contains a field which uses the function
$$Total to calculate the total of all the repeated fields TBAmountField contained within the
detail line.

;;Part Having Total and Scroll attribute


[Part: TB Part]
Lines : TB Title, TB Details
Repeat : TB Details: TB Groups
Bottom Line : TB Totals
Total : TB Amount Field
Scroll : Vertical
CommonBorder: Yes

525
Advanced Reporting and Printing

;;Field using Built-in Function $$Total


[Line: TB Totals]
Use : TB Details
Local : Field : TB Name Field : Set as: "Totals"
Local : Field : TB Amount Field: Set as: $$Total: TBAmountField
Border : Flush Totals
The output screen shot for the Tabular Report is given below:

Designing Interactive Tabular Report


A tabular Report can be made interactive by incorporating the following elements within the
Report:
 Adding Button/Key to Form definition
 Adding Keys to Line Definition
 Adding Explosions to Line Definition

Adding Button/Key to Form Definition


A Tabular Report can be made interactive by adding Button/Key to Form Definition.
Following are the some of the significant features that can be achieved with this approach:

526
Advanced Reporting and Printing

 A Report can be viewed for a specific period


 When Multiple companies are loaded, by click of a button same Report can be
viewed for any of the active companies
Example:
In the following code snippet, the default Buttons Change Company and F2Change period can
be used to view the Report for different loaded company or given specific period.
The keys Form Remove Line and Form Last Removed can be used to remove or bring back
the last removed line to Report.
[Form: TB]
Button : F2ChangePeriod, ChangeCompany
Keys : Form Remove Line, Form Show Last Removed Line
Parts : TB Title, TB Part

The following screen shot is displayed when a user is clicked button to change the period to
view the report for a given period:

Adding Keys to Line Definition


A Tabular Report can be made interactive by adding Keys to Line Definition. Following are
the some of significant features that can be achieved with this approach.

527
Advanced Reporting and Printing

 Display of a Specific Line of a Report can be controlled


 From a Report user can navigate to other Report for altering the master. If any master
is altered that will reflect back in the Report immediately
Example:
The Key ‘AlterGrp’ is added to the Line, with this by pressing CTRL + ENTER a Group
alteration screen will be opened and user can alter the Group. The change will immediately
reflect in the Report.
[Line: TB Details]
Fields : TB Name Field, TB ParName Field
Right Field : TB Dr Amt Field, TB Cr Amt Field
Explode : TB Group Explosion: $$IsGroup AND +
$$KeyExplode
Option : Alter Grp : $$IsGroup

[Field: TB Name Field]


Use : Name Field
Set as : $Name
Variable : SVGroup

[!Line : Alter Grp]


Key : Alter Grp

[Key : Alter Grp]


Key : Ctrl + Enter
Action: Alter : Grp

[Report: Grp]
Delete: Object
Add : Object : Group
Use : Group
Form : TSPL Grp

528
Advanced Reporting and Printing

[Form : TSPL Grp]


Use : Group

The following screen shot is displayed when a user clicks CTRL + ENTER on line Sales
Accounts:

Adding Explosions to Line Definition


Tally.ERP 9 allows the user to display additional information about the current line object
when the key combination SHIFT + Enter is pressed. This functionality is referred to as an
explosion in Tally.ERP 9.The default key definition “Line Explode” triggers the action
“Explode” when the key combination SHIFT + Enter is pressed. The attribute Explode and
Indent of Line definition, and the $$KeyExplode function is used for the same.
Line attribute – Explode
The attribute ‘Explode’ refers to an attribute of the line, which is used to take the current data
from the Line Object. A Part is displayed after the process of explosion is complete.
Syntax
Explode : <Part Name> [: <Logical Condition>]
Where,
<Part Name> is the name of the Part which displays the additional information about the Line
object

529
Advanced Reporting and Printing

<LogicalCondition> is an optional component. If this component is used and condition


evaluates to true, then it will result in an explosion.
The Function of $$KeyExplode is a function gives the current status of the keys Shift and
Enter. This is used as a condition to check if the user has pressed the Shift+Enter Keys.

Example:
In the following code snippet the part “TB Group Explosion” is exploded from each line “TB
Details”. The Explode is evaluated when the Object pertaining to the line is a group and the
keys Shift+Enter is pressed. The part “TB Group Explosion” again repeats the line “TB
Details Explosion” over a collection which in turn explodes the same part “TB Group Explo-
sion” based on the same condition as above. The explodes happen recursively till the line
object is a ledger object.
[Line: TB Details]
Fields : TB Name Field, TB ParName Field
Right Fields: TB Dr Amt Field, TB Cr Amt Field
Explode : TB Group Explosion : $$IsGroup AND +
$$KeyExplode
[Part: TB Group Explosion]
Lines : TB Details Explosion
Repeat : TB Details Explosion : TB GroupsLedgers
Scroll : Vertical

[Line: TB Details Explosion]


Fields : TB Name Field, TB ParName Field
Right Fields : TB Dr Amt Field, TB Cr Amt Field
Explode : TB Group Explosion : $$IsGroup AND $$KeyExplode
Indent : 2 * $$ExplodeLevel
Local : Field : Default : Delete: Border

[Collection: TB GroupsLedgers]
Collection : TB Groups, TB Ledgers

530
Advanced Reporting and Printing

[Collection: TB Groups]
Type : Group
Child Of : #SVGroup
Filter : Zero Filter
Fetch : Name, ClosingBalance

[Collection: TB Ledgers]
Type : Ledger
Child Of : #SVGroup
Filter : TSPL Zero Filter
Fetch : Name, ClosingBalance

[System: Formula]
Zero Filter : $ClosingBalance > 0 AND NOT $$IsLedgerProfit

531
Advanced Reporting and Printing

Designing a Drill Down/Hierarchical Report


A Tally application provides a simple way of navigating from one report to another which is
commonly referred to as a drill down. A Drill Down facility moves from one report to the
other to give a detailed view based on the selection in the current report. A user can return to
the first Report from the detailed view. A typical drill down in Tally.ERP 9 starts from the
Report and reaches to Voucher Alteration screen.

A Hierarchical Report can be designed by incorporating the following changes to a Tabular


Report.
 Navigating to another Report by press of Enter Button by using Display attribute of a
Field and a Variable to hold information on the basis of which the data is gathered
and displayed dynamically in the child report.
 Variable declaration at the child Report level
 Constructing the Collection based on the Variable value in the child report
Example:
The following code snippet demonstrates the Drill down action, which is based on the Group
Name displayed in the field. The Drill down action is achieved by specifying the two attributes
Variable and Display at the field level.
[Field: TB Name]
Use : Name Field
Set as : $Name
Variable : GroupVar
Display : TB: $$IsGroup

This Volatile attribute for this variable is set to “Yes” i.e this variable retains previous value
from the caller scope. The same variable is declared and is available in the called Report.
[Variable: Group Var]
Type : String
Default : ""
Volatile : Yes

[Report: TB]
Form : TB
Variable : GroupVar

532
Advanced Reporting and Printing

The called report displays the data from a collection which uses the value of the variable in the
ChildOf attribute of the collection.
[Collection: Collection]
Type : Group
Childof : ##GroupVar

The following screen is displayed when the user invokes the Report.

Figure 12.1 Trial Balance Report

When the key Enter is pressed by the user, the next screen displays the Sub Groups of the
current Group as shown below:

533
Advanced Reporting and Printing

Figure 12.2 Trial Balance with Subgroup Details

Exercise 12.1:
Objective
The objective of this program is to develop a Report to display Stock Group/Stock item
Details like Name, Opening, Inwards, Outwards and Closing quantities with drill-down
facility till Voucher.

Capabilities Used
 Collection definition with attributes Type, Childof, Filter, Fetch and Collection
 Part definition with attributes Scroll, Repeat and Total
 Field Definition with attributes Display, Variable and Switch
 Built-in Functions $$KeyExplode and $$Total

534
Advanced Reporting and Printing

Code
[Report: Exer HD Stock Summary]
Form : Exer HD Stock Summary
Title: "Stock Summary"
;; Declaring a Local Variable which holds the variable name while in drill down as the same Report is being invoked
every time the user drills down from a Group Name
Variable: Exer HD GroupName: String

[Form: Exer HD Stock Summary]


Parts : Form SubTitle, Exer HD Stock Summary
;; Default Buttons and Keys associated here
Buttons : ExplodeFlag, F2ChangePeriod, ChangeCompany
Keys : ChangePeriod
Local : Field : Form SubTitle : +
Info : "Report Design - Stock Summary"

[Part: Exer HD Stock Summary]


Lines : Exer HD SS Title, Exer HD SS Detail
BottomLines : Exer HD SS Total
Repeat : Exer HD SS Details: Exer HD SS GroupsItems

;; Part Attribute 'Total' accepts a list of Field Names on which Totals are to be accumulated
Total : Exer HD SS Open Qty, Exer HD SS Inwd Qty, +
Exer HD SS Outw Qty, Exer HD SS Clsg Qty
Scroll : Vertical
CommonBorder : Yes

[Line: Exer HD SS Title]


Use : Exer HD SS Details
Local : Field : Default : Type : String
Local : Field : Default : Align : Centre

535
Advanced Reporting and Printing

Output

Program Explanation
The part Exer HD Stock Summary has three lines. The topmost line Exer HD SS Title is
utilized for displaying column Titles and is using the line Exer HD SS Details, so it will
inherit all the attributes of the line Exer HD SS Details. At line Exer HD SS Title we have
localized all the fields and set the values by using attribute ‘Set as’.
At part Exer HD Stock Summary, Total attribute is specified with the fields Exer HD SS
Open Qty, Exer HD SS Inwd Qty, Exer HD SS Outw Qty, and Exer HD SS Clsg Qty to
calculate running total at the bottom Line Exer HD SS Total.
At part Exer HD Stock Summary, second line Exer HD SS Details has been repeated over
collection Exer HD SS GroupsItem. Exer HD SS GroupsItems is a Union collection and at
any particular point of time the Objects were gathered from Collections Exer HD SS Group
and Exer HD SS Items. The objects for these collections are depending on the Childof
condition which in turn depends on Field acting as Variable ExerHDGroupName. The Value
of Variable ExerHDGroupName is decided at the Field Exer HD SS Name.
At the Field Exer HD SS Name the Enter key will display a Report Exer HD Stock
Summary. in case of StockGroup object or will display Report Item Monthly Summary in
case of Stock Item object. The attribute Variable will feed appropriate value the childof
condition of Collection Exer HD SS GroupsItem.

536
Advanced Reporting and Printing

The Line Exer HD SS Details is having exploded part if Shift + Enter key is pressed or the
F1 button is clicked and the current object is Stock Group. The Line Exer HD SS Details
Explosion inside the exploded part again recursively exploded till encounters Stock Group
object.
The Function $$KeyExplode is used to have indent at explode part.

12.1.2 Columnar Reports


Basically the columnar reports enable the display of additional columns in the report with or
without user intervention. The entire set of fields can be repeated over a different period or
active companies as per user inputs. The column based reports primarily work on the concept
of Repeat Variables.
A Repeat Variable is a simple variable that can hold multiple values based on implicit index.
These values can be populated using user inputs or from method values of multiple objects of
a collection. The Repeat attribute of the variable allows the specification of the same.
The number of columns are added to the report based on the no of values available in the
Repeat Variable. The Repeat Variable over which a column is to be repeated is specified by
using the Repeat attribute of the Report.
The set of fields to be repeated is specified using the Repeat attribute of the line.
There are mainly the following types of Columnar Reports available in Tally
 MultiColumn Report – In this type of report one Column is added at a time, based
on the values provided to the Repeat variable by the user in an Auto Report.
 AutoColumn Report - In this type of a Report Multiple columns are added in one
go based on the options selected by the user in an Auto Report invoked on click of a
button. The options selected determine the no of values populated into the Repeat
variable. The no of columns is governed by the no of values available in the Repeat
variable
 Automatic Auto Columns – This is also an Auto column Report where the options
are preset prior to the report invocation and does not depend upon the user interven-
tion. i.e the repeat variable and the collection to be used for populating the variable is
preset at the report level.
 Matrix Reports –In a traditional auto/automatic auto column reports the columns
are repeated over a predefined variable and the method values within the detail line
is extracted based on the internal linking with the variable. In cases where the col-
umns are to be repeated on a variable defined by programmer, and the method values

537
Advanced Reporting and Printing

in detail line are to be accessed based on column and row values explicitly, matrix
reports are designed.

Highly recommended to refer to the topic “Implication of Repeat Variables in


Columnar Reports” within the chapter “Variable Framework” before proceed-
ing on to the next section.
Auto Reports are created by specifying the Auto attribute as “Yes”. This
attribute is used to tell the system that it is a specialized report which does not
instantiate its own variables and objects. It also does not bring the confirmation
box 'Accept' when the report is accepted.

Designing a Multi Column Report


In a multicolumn report the lines in detail section is repeated over a collection and a column/
field is repeated over a Repeat variable. The values are provided to the repeat variable using a
separate report. This report is referred to as the column report. The column Report is used to
capture the user inputs like Period, Company Name, Stock Valuation etc on which column is
generated.
Following attributes are used at different components of a Report to incorporate the multi
column feature.

Report attribute – Column Report


The attribute Column Report is used to specify the report name which is invoked to accept the
user inputs. These inputs provide values to the various repeat variables over which a column/
field is repeated.
Syntax
ColumnReport: <Column Report Name>
Where,
<Column Report Name> is the name of the report which is used to obtain the user input

Report attribute-Repeat
The Repeat variable names over which the column/field needs to be repeated is specified at the
report level by using the Repeat attribute. This is a list type variable which accepts a list of
variable names separated by comma. These variables are system variables.
Both of these attributes Column Report and Repeat used together govern the display of the
buttons New Column, Alter Column and Delete Column on the screen. These buttons
control the appearance of addition, alteration and deletion of columns based on the user inputs
within the column report.

538
Advanced Reporting and Printing

Syntax
Repeat : <Variable names>
Where ,
<Variable names> is the list of repeat variable names separated by commas.

Line attribute-Repeat
In a multicolumn report, the report repeats a single field or a set of fields which is collectively
referred to as columns. This is specified using the Repeat attribute of the line. This attribute
provides the field names contained within the line which are to be repeated. The method
values referred to within the fields are accessed based on the internal linking with the corre-
sponding Repeat variable value.

Example:
Incorporating Multi Column Feature to Simple Trial Balance report.

Step 1 : Using Column Report & Repeat attribute at the Report


The column report attribute specifies the report name “Multicolumns” which is used to accept
values for the repeat variables “SVCurrentCompany, SVFromDate and SVToDate” specified
using the repeat attribute.

These two attributes together add the three buttons as discussed above
[Report: MulCol Trial Balance]
ColumnReport: MultiColumns
Repeat : SVCurrentCompany, SVFromDate, SVToDate

539
Advanced Reporting and Printing

Step 2: Modifying the values of Repeat Variables within the column report
By clicking new column button, the report MultiColumns is displayed. This report contain
fields to accept user inputs corresponding to the Repeat variables. The modifies attribute of
the field is used to reflect the values entered in the fields into the variables.
[Field: MultiFromDate]
Use : Uni Date Field
Modifies : SVFromDate

[Field: MultiToDate]
Use : Uni Date Field
Modifies: SVToDate

[Field: MultiCompany]
Use : Name Field
Modifies : SVCurrentCompany

540
Advanced Reporting and Printing

Table : Company

Figure 12.3 Column Details for Multi Column Report

Step 3: Specifying the fields/column to be repeated


The line in detail section is repeating over the objects of a collection. Within this line a field or
a set of fields referred to as column is repeated over the Repeat variables specified at the
Report level.

The line “MulCol TB Details” is repeated over the collection “MulCol TB GroupLed”
[Part: MulCol TB Details]
Lines : MulCol TB Details
BottomLines: MulCol TB Total
Repeat : MulCol TB Details : MulCol TB GroupLed

The field “MulCol TB Amount Field” within the line MulCol TB Details “ is the field which is
repeated.

541
Advanced Reporting and Printing

[Line: MulCol TB Details]


Field : MulCol TB Name Field, MulCol TB Amount Field
Repeat : TSPL MulCol TB Amount Field

If a set of fields are to be repeated then these must be components of the main field which is
specified in the repeat attribute of the line. The field “MulCol TB AmountField” is a
compound field containing the fields “MulCol TB DrAmt Field and MulCol TB CrAmt Field”
[Field: MulCol TB AmountField]
Fields : MulCol TB DrAmt Field, MulCol TB CrAmt Field

Figure 12.4 Multi Column Report

Designing an Auto Column Report


In this type of a Report Multiple columns are added in one go based on the options selected by
the user in a different report invoked on click of a button. The options selected determine the
no of values populated into the Repeat variable. The no of columns is governed by the no of
values available in the Repeat variable.
Following TDL elements are used at different components of a Report to incorporate the auto
column feature.

542
Advanced Reporting and Printing

Report attribute – Repeat


The Repeat variable names over which the column/field needs to be repeated is specified at the
report level by using the Repeat attribute. This is a list type variable which accepts a list of
variable names separated by comma. These variables are system variables.
Syntax
Repeat : <Variable names>
Where,
<Variable names> is the list of repeat variable names separated by commas.

Line attribute – Repeat


In an auto column report, the report repeats a single field or a set of fields which is collectively
referred to as columns. This is specified using the Repeat attribute of the line. This attribute
provides the field names contained within the line which are to be repeated. The method
values referred to within the fields are accessed based on the internal linking with the corre-
sponding Repeat variable value.

Action – Auto Column


A button is used to invoke a report for accepting the user inputs in a separate report.This report
is referred to as a Auto Column report. The Action used to invoke this is “AutoColumns”
Syntax
Action : Auto Columns : <Auto Column Report Name>
Where,
<Auto Column Report Name > is the name of the auto column report which is invoked to
accept user inputs

Form Attribute – Output


This attribute is used within the autocolumn report to specify the variable name which is to be
sent and used for repeating columns in the calling report
Syntax
Output:<FieldName>
Where,
<FieldName> is the field name which stores the variable name which is to be used in the
calling report for repeating columns.

Variable Attribute – Repeat


The attribute Repeat for a variable accepts collection name and optional method name as
parameters. Method value of each object of the collection will be picked up and stored in the

543
Advanced Reporting and Printing

variable based on implicit index. In case method name is not specified the variable name is
considered as the method name and picked up from the collection.
Syntax
[Variable: <Variable Name>]
Repeat: <Collection Name>[:<Method Name>]
Where,
<Variable Name> is the name of the variable.
<Collection Name> can be an expression which evaluates to a collection name.
<Method name> is the name of the method whose value needs to be picked up from each
object of the collection. If not specified, variable name is considered as the method name.

Example:
Incorporating Auto Column Feature to Simple Trial Balance report in order to generate
columns based on periodicity or active companies based on user inputs

Step 1: Specifying the Repeat attribute of the Report


The Repeat specification at the report specifies the variable names SVCurrentCompany,
SVFromDate, SVToDate over which the column/field needs to be repeated.
[Report: AutoCol Trial Balance]
Repeat: SVCurrentCompany, SVFromDate, SVToDate

Step 2 :Displaying the Auto Column report using Action Auto Columns
The Button AutoButton is added to Form. Through this Button, the Report “AutoColumns
Report” is invoked for user intervention.
[Form: AutoCol Trial Balance]
BottomButton : AutoButton

[Button: AutoButton]
Key : Alt+N
Action : Auto Columns : AutoColumns Report
Title : $$LocaleString : "Auto Column”

544
Advanced Reporting and Printing

Figure 12.5 Auto Column Report

545
Advanced Reporting and Printing

Step 3: The Auto Column Report to accept user inputs


When the user clicks on the button the following report is invoked

Figure 12.6 Auto Column report

Within this, the user will be given with options like ‘Days’,’ Monthly’, Yearly’ ‘Company’ etc
based on which the columns are repeated. Based on any of these options selected the Collec-
tion name, Variable name, periodicity etc will be populated with values. The table displayed
for selection is created using the collection of external Objects as defined below
[Collection: Auto Columns]
Title : $$LocaleString:"Column Details"
Object: CurrentCompany, Quarterly, Monthly,Yearly,HalfYearly
Format: $$Name, 15
The objects are defined which provide values for the methods VarName,CollName and perio-
dicity.
[Object: CurrentCompany]
Name : $$LocaleString:"Company"
VarName : "SVCurrentCompany"

546
Advanced Reporting and Printing

CollName : "List of Primary Companies"


Periodicity : ""
In case the collname is “List of Primary Companies” periodicity is set is null and the VarName
is “SVCurrentCompany”
[Object: Quarterly]
Name : $$LocaleString:"Quarterly"
VarName : "SVFromDate, SVToDate"
CollName : "Period Collection"
Periodicity: "3 Month"

[Object: HalfYearly]
Name : $$LocaleString:"Half-Yearly"
VarName : "SVFromDate, SVToDate"
CollName : "Period Collection"

[Object: Monthly]
Name : $$LocaleString:"Monthly"
VarName : "SVFromDate, SVToDate"
CollName : "Period Collection"
Periodicity: "Month"

[Object: Yearly]
Name : $$LocaleString:"Yearly"
VarName : "SVFromDate, SVToDate"
CollName : "Period Collection"
Periodicity: "Year"
In case the collname is “Period Collection” periodicity is set as per option selected from the
table ie yearly, halfyearly, monthly etc and the VarName is "SVFromDate, SVToDate"

Columns can be repeated over any Repeat Variable which can assume values
from any collection. This is not limited to default collections as used above. We
will be covering such examples in the section on Matrix Reports.

547
Advanced Reporting and Printing

When the user selects any one of the options required, the system variables need to be
modified so that, the columns can be generated in the parent Report on the basis of these
values.

Field Select Auto displaying the table to select options Company, Monthly, HalfYearly,
Quarterly, Yearly
[Field: SelectAuto]
Use : Short Name Field
Table : TSPLAutoColumns
Show Table : Always

Invisible Field AutoColumns which sets the field with the method Varname as per object
selected in the table.ie if the object selected in the table is Company the field will be set with
the value SVCurrentCompany,if the object selected is either Monthly, Yearly etc., the field
will be set with the value SVFromDate, SVToDate
[Field: AutoColumns]
Use : Short Name Field
Invisible : Yes
Set as : $$Table:SelectAuto:$VarName
Set always : Yes
Skip : Yes

Invisible Field CollName which sets the field with the method CollName as per object
selected in the table. ie if the object selected in the table is Company the field will be set with
the value List of Primary Collection, if the object selected is either Monthly, Yearly etc the
field will be set with the value Period Collection.
[Field: CollName]
Use : Short Name Field
Invisible : Yes
Set as : $$Table:TSPLSelectAuto:$CollName
Modifies : DSPRepeatCollection
Set always : Yes
Skip : Yes

548
Advanced Reporting and Printing

Further this value will modify the value of the default variable DSPRepeatCollection. The
repeat variables SVCurrentCompany, SVFromDate and SVToDate assume multiple values
from the collection name as available within DSPRepeatCollection at that instance.
[Variable: SVCurrentCompany]
Volatile : Yes
Repeat : ##DSPRepeatCollection

Invisible Field SetPeriodicity which sets the field with the method Periodicity as per object
selected in the table. ie if the object selected in the table is “Company” the field will be set
with null “”, if the object selected is either Monthly, Yearly etc. the field will be set with the
value 3 month, month, year etc.
[Field: SetPeriodicity]
Use : Short Name Field
Invisible : Yes
Set as : If NOT $$IsEmpty:$$Table: SelectAuto:+
$Periodicity then $$Table: SelectAuto:+
$Periodicity else "Month"
Set always : Yes
Modifies : SVPeriodicity

Further this value will modify the value of the default variable “SVPeriodicity”. This variable
value is used within the Repeat attribute of the default collection “Period Collection”. The
objects are populated in period collection based on Periodicity.
[Collection: Period Collection]
Type : Period
Repeat : ##SVPeriodicity

The value available in the field “AutoColumns” is output to the calling report by using the
Output Attribute. In this example it is either “SVCurrentCompany” or “SVFromDate,SVTo-
Date”
[Form: AutoColumns]
No Confirm : Yes
Output : AutoColumns

549
Advanced Reporting and Printing

Step 4: Specifying the fields/column to be repeated


The line in detail section is repeating over the objects of a collection. Within this line a field or
a set of fields referred to as column is repeated over the Repeat variables specified at the
Report level.

The line AutoCol TB Details is repeated over the collection AutoCol TB GroupLed
[Part: AutoCol TB Details]
Lines : AutoCol TB Details
BottomLines: AutoCol TB Total
Repeat : MulCol TB Details : MulCol TB GroupLed

The field AutoCol TB Amount Field within the line AutoCol TB Details is the field which is
repeated.
[Line: AutoCol TB Details]
Field : AutoCol TB Name Field, AutoCol TB Amount Field
Repeat: AutoCol TB Amount Field

If a set of fields are to be repeated then these must be components of the main field which is
specified in the repeat attribute of the line. The field “AutoCol TB AmountField” is a
compound field containing the fields “AutoCol TB DrAmt Field and AutoCol TB CrAmt
Field”
[Field: AutoCol TB AmountField]
Fields : AutoCol TB DrAmt Field, AutoCol TB CrAmt Field

In order to summarize the difference between two approaches of columnar reports let us refer
to the table below

Multicolumn Report AutoColumn Report


At a time only one value is added into the Multiple values are added to the repeat
repeat variable by accepting user inputs variable at one go based on the values
from the column report. available in the collection. This collection
name is available in the repeat specifica-
tion of the collection

550
Advanced Reporting and Printing

The attribute “Column Report” and The button with action specification
“Repeat” specification at the report level “AutoColumn” is added in the main form
adds the buttons “Add/Alter/Delete Col-
umn” automatically
The report to be invoked for user inputs is The report to be invoked for user inputs is
specified in the Column attribute of the specified as a parameter to the Action
report Auto Column
The column reports accepts the values for The autocolumn reports accepts the user
variables from the user inputs for the collection name which in
turn is used to populate the value of the
variable
The values provided to the variables is The output attribute of the form specifies
automatically used to repeat a column in the variable name which is to be sent and
the calling report used for repeating columns in the calling
report
Exercise 12.2
Objective
The objective of this program is to develop Stock Summary Multi column Report having
columns Name, Opening, Inwards, Outwards and Closing quantities with columnar capability.
Capabilities Used
 Report attribute Column Report and Repeat
 Form attribute Output
 Part definition with attributes Scroll, Repeat and Total
 Line attribute Repeat
 Field Definition with attributes Display, Variable and Switch
 Collection definition with attributes Type, Childof, Filter, Fetch and Collection
 Action Auto Column
 Built-in Functions $$KeyExplode, $$IsCommon and $$Total

551
Advanced Reporting and Printing

Code
[Report: Exer Columnar Stock Summary]
Form : Exer Columnar Stock Summary
Title : $$LocaleString:"Stock Summary"
Repeat : SVCurrentCompany, SVFromDate, SVToDate
/* When the attribute Column Report is mentioned, the attribute Repeat should also be mentioned. The New Column,
Alter Column and Delete Column buttons will automatically get activated once Column Report & Repeat attributes are
mentioned together in the report.*/
ColumnReport: Exer CSS MultiColumns
Variable : IsItemWise, SVPeriodicity
Variable : Exer CSS Group: String
;; PrintSet At Report Definition sets the Variable Value in Print Mode
PrintSet : Report Title : $$LocaleString:"Trial Balance"
Set : IsItemWise : No

[Form: Exer Columnar Stock Summary]


Buttons : F2ChangePeriod, ChangeCompany, ItemWiseButton
Keys : ChangePeriod
BottomButton: Exer CSS AutoButton, BlankButton, InvReports,+
AcctReports, ReportOperations, FilterButton, +
ValueButton
Buttons : PrintButton, ExportButton, UploadButton, MailButton
Bottom Toolbar Buttons: BottomToolBarBtn1, BottomToolBarBtn8,+
BottomToolBarBtn9, BottomToolBarBtn10, +
BottomToolBarBtn11,BottomToolBarBtn12
Parts : Exer CSS Title, Exer CSS Details
Page Break : DSP ClPageBreak, Exer CSS OpPgPart
Background : Released Pale Yellow
Option : Exer CSS Prn : $$InPrintMode

[!Form: Exer CSS Prn]


/*For enabling Titles during Printing, Form Level Optional parts Company Name, Address and Report Title are used
from defTDL.*/
Add : Parts : At Beginning : DSP CompanyName, +
DSP CompanyAddress, DSP ReportTitle
Space Left : 0.25 inch

552
Advanced Reporting and Printing

[Part: Exer CSS OpPgPart]


Parts : DSP CompanyName, DSP CompanyAddress, DSP ReportTitle,+
Exer CSS Title
Vertical : Yes

;; Every continuous page should have the above parts during Printing
[Part: Exer CSS Title]
Lines : Exer CSS T
itle1, Exer CSS Title2, Exer CSS SubTitle
Border : Thin Top

[Line: Exer CSS Title1]


Fields : Name Field, Exer CSS Open
Repeat : Exer CSS Open
Local : Field : Default : Type : String
Local : Field : Default : Align : Center
Local : Field : Exer CSS Open : Lines : 0
Local : Field : Exer CSS Open : Border : Thin Left
;; This Line is made Invisible in Print Mode only if Columns selected are of single company
Invisible : $$IsCommon:SVCurrentCompany AND $$InPrintMode

[Line: Exer CSS Title2]


Use : Exer CSS Title1
Local : Field : Default : Type : String
Local : Field : Default : Align : Center
Local : Field: Name Field: Set as: +
$$LocaleString:"Particulars"
Local: Field: Name Field: Style : Normal Bold
Local: Field: Name Field: WideSpaced: Yes
Local: Field: Exer CSS Open: Set as : @@DSPDateStr
Local: Field: Exer CSS Open: Border : Left Full Thin Bottom
/* DSPFDateStr is the Default Formula which displays the values present in both the date variables - SVFromDate &
SVTodate */

553
Advanced Reporting and Printing

[Line: Exer CSS SubTitle]


Fields: Name Field, Exer CSS Qty
Repeat: Exer CSS Qty
Local: Field: Default : Style : Normal
Local: Field: Default : Align : Centre
Local: Field: Default : Type : String
Local: Field: Name Field : Set as: ""
Local: Field: Exer CSS Open: Set as: $$LocaleString:"Opening"
Local: Field: Exer CSS Inwd: Set as: $$LocaleString:"Inward"
Local: Field: Exer CSS Outw: Set as: $$LocaleString:"Outward"
Local: Field: Exer CSS Clsg: Set as: $$LocaleString:"Closing"
Local: Field: Exer CSS Qty : Border: Thin Left
Border: Thin Bottom

[Part: Exer CSS Details]


Lines : Exer CSS Details
BottomLines : Exer CSS Total
Repeat : Exer CSS Details: Exer CSS GroupItem
Total : Exer CSS Open, Exer CSS Inwd, Exer CSS Outw, +
Exer CSS Clsg
Scroll : Vertical
CommonBorder: Yes
Float : Yes
/* Part Level Page Breaks is introduced to have Page Totals at the beginning (except ;; first page) and end (except last
page) of every page*/
Page Break : Exer CSS ClPgLine, Exer CSS OpPgLine
Option : Exer CSS Details Item : ##IsItemWise
;; The optional part is selected when Itemwise is selected by the user.

[!Part: Exer CSS Details Item]


Repeat: Exer CSS Details: Exer CSS Item
Local : Collection: Exer CSS Item : BelongsTo : Yes
Local : Field : Default: Style: Normal

554
Advanced Reporting and Printing

;; If Itemwise Option is selected by the user, Collection should have attribute BelongsTo set to Yes
;; as the Stock Items pertaining to all the Groups and Sub-Groups needs to be displayed together

[Line: Exer CSS ClPgLine] ;; Line for Closing Page Totals


Use : Exer CSS Details
Delete : Fields: Exer CSS Amount Field
Add : Fields: Exer CSS AmountSTField
Delete : Repeat: Exer CSS AmountSTField
Add : Repeat: Exer CSS AmountSTField
Local : Field : Default : Style : Normal Bold
Local : Field : Default : Border : Totals
Local : Field : Exer CSS Name : Set as : "Carried Over"
Local : Field : Exer CSS Name : WideSpaced: Yes
Local : Field : Exer CSS Name : Delete : Border
Local : Field : Exer CSS Open : Set as: $$Total:ExerCSSOpen
Local : Field : Exer CSS Inwd : Set as: $$Total:ExerCSSInwd
Local : Field : Exer CSS Outw : Set as: $$Total:ExerCSSOutw
Local : Field : Exer CSS Clsg : Set as: $$Total:ExerCSSClsg
Space Top : 1

[Line: Exer CSS OpPgLine] ;; Line for Opening Page Totals


Use : Exer CSS ClPgLine
Local : Field : Exer CSS Name : Set as : "Brought Foward"
Local : Field : Exer CSS Open: Delete : Border
Local : Field : Exer CSS Inwd: Delete : Border
Local : Field : Exer CSS Outw: Delete : Border
Local : Field : Exer CSS Clos: Delete : Border
Space Top : 0
Space Bottom : 1

[Field: Exer CSS QtySTField] ;;New Field Definition for the Page Totals
Fields : Exer CSS OpenST, Exer CSS InwdST, Exer CSS +
OutwST, Exer CSS ClsgST
Border : Thin Left

555
Advanced Reporting and Printing

[Field: Exer CSS OpenST]


Use : Exer CSS Open

[Field: Exer CSS InwdST]


Use : Exer CSS Inwd

[Field: Exer CSS OutwST]


Use : Exer CSS Outw

[Field: Exer CSS ClsgST]


Use : Exer CSS Clsg

[Line: Exer CSS Details]


Fields : Exer CSS Name, Exer CSS Qty
Repeat : Exer CSS Qty
Local: Field: Exer CSS Name: Set as: $$Name
Local: Field: Exer CSS Open: Set as: $OpeningBalance
Local: Field: Exer CSS Inwd: Set as: $TrPurcQty
Local: Field: Exer CSS Outw: Set as: $TrSaleQty
Local: Field: Exer CSS Clsg: Set as: $ClosingBalance
;; Repeat Attribute of Line will position the Field to the Right, as if it is a Right Field.

[Field: Exer CSS Name]


Use : Name Field
Variable: Exer CSS Group
Display : Exer Columnar Stock Summary: $$IsGroup
Option : Exer CSS ItemName : $$IsLedger

[!Field: Exer CSS ItemName]


Variable : StockItemName
Display : Item Monthly Summary
Style : Normal Italic

556
Advanced Reporting and Printing

[Field: Exer CSS Qty]


Fields : Exer CSS Open, Exer CSS Inwd, Exer CSS Outw, +
Exer CSS Clsg
Border : Thin Left
Display: Exer Columnar Stock Summary: $$IsStockGroup
Display: Item Monthly Summary : $$IsStockItem

[Field: Exer CSS Open]


Use : Qty Primary Field
Style : Normal

[Field: Exer CSS Inwd]


Use : Qty Primary Field
Style : Normal

[Field: Exer CSS Outw]


Use : Qty Primary Field
Style : Normal

[Field: Exer CSS Clsg]


Use : Qty Primary Field
Style: Normal

[Line: Exer CSS Total]


Use : Exer CSS Details
Local : Field : Default : Style : Normal Bold
Local : Field : Exer CSS Name : Set as : "GRAND TOTAL"
Local : Field : Exer CSS Name : WideSpaced: Yes
Local : Field : Exer CSS Name : Align : Centre
Local : Field : Exer CSS Open : Set as : $$Total:ExerCSSOpen
Local : Field : Exer CSS Inwd : Set as : $$Total:ExerCSSInwd
Local : Field : Exer CSS Outw : Set as : $$Total:ExerCSSOutw
Local : Field : Exer CSS Clsg : Set as : $$Total:ExerCSSClsg

557
Advanced Reporting and Printing

Border : Flush Totals


Fixed : Yes
Space Top : 1

;; Collection Definition
[Collection: Exer CSS GroupItem]
Collection : Exer CSS Group, Exer CSS Item

[Collection: Exer CSS Group]


Type : Stock Group
Child Of : ##ExerCSSGroupFetch : Name, OpeningBalance, TrPurcQty,
TrSaleQty, ClosingBalance

[Collection: Exer CSS Item]


Type : Stock Item
Child Of : ##ExerCSSGroup
Fetch : Name, OpeningBalance, TrPurcQty, TrSaleQty, ClosingBalance

; Report for displaying Column Option


[Report: Exer CSS MultiColumns]
Title : $$LocaleString:"Column Details"

[Form: Exer CSS MultiColumns]


No Confirm : Yes
Full Width : No
Space Right : 0.25
Background : @@SV_UNBLUE
Parts : Exer CSS MultiColumns
Option : Small Size Form

[Part: Exer CSS MultiColumns]


Lines : Form SubTitle, Exer CSS Company, Exer CSS FromDate,
Lines : Exer CSS ToDate
Local : Field : Form SubTitle: Info : $$LocaleString:"Column Details"

558
Advanced Reporting and Printing

{Line: Exer CSS Company]


Fields : Short Prompt, Exer CSS Company
Local : Field : Short Prompt : Info : $$LocaleString:"Company :"
SpaceBottom : 1
Invisible : $$SelectedCmps = 1
;; SelectedCmps is a function which returns the number of selected companies It requires no parameters.
;; This means that if the Selected Companies equals to 1 then this line should be made invisible

[Field: Exer CSS Company]


Use : Name Field
Modifies : SVCurrentCompany
Table : Company
Show Table : Always

;; Modifies alters the Value of a Variable to be used subsequently


[Line: Exer CSS FromDate]
Fields : Short Prompt, Exer CSS FromDate
Local : Field : Short Prompt : Info : $$LocaleString:"From Date:"
SpaceBottom : 1

[Field: Exer CSS FromDate]


Use : Uni Date Field
Modifies : SVFromDate
Width : 9

[Line: Exer CSS ToDate]


Fields : Short Prompt, Exer CSS ToDate
Local : Field : Short Prompt : Info : $$LocaleString:"To Date :"
SpaceBottom : 0.25

[Field: Exer CSS ToDate]


Use : Exer CSS FromDate
Modifies : SVToDate

559
Advanced Reporting and Printing

;; Changes to achieve AutoColumn


[Button: Exer CSS AutoButton]
Key : Alt + N
Action : Auto Columns : Exer CSS AutoColumns
Title : $$LocaleString:"Auto Column"
Inactive : $$NumItems:ExerCSSAutoColumns < 1
;; Action 'Auto Columns' is an action which takes a report as its value and gives auto columns in the base report
;; accordingly. AutoColumns is a report being displayed when the button Exer CSS AutoButton is clicked.

[Collection: Exer CSS Auto Columns]


Title : $$LocaleString:"Column Details"
Object : Exer CSS CurrentCompany, Exer CSS Quarterly, +
Exer CSS Monthly, Exer CSS Yearly, Exer CSS HalfYearly
Filter : Belongs
Format : $$Name, 15
/* Belongs is a system formula which filters the objects based on the value of the Methods BelongsIf of all the objects;
Function Name returns the Name of any given objects*/

[Object: Exer CSS CurrentCompany]


Name : $$LocaleString:"Company"
VarName : "SVCurrentCompany"
CollName : "List of Primary Companies"
BelongsIf : $$NumItems:ListOfPrimaryCompanies > 1
IsAgeWise : No
Periodicity : ""
/*Function NumItems returns the number of selected companies BelongsIf is a method of object Exer CSS CurrentCom-
pany, which is used to control the display of the object in the collection*/

[Object: Exer CSS Quarterly]


Name : $$LocaleString:"Quarterly"
VarName : "SVFromDate, SVToDate"
CollName : "Period Collection"
BelongsIf : "Yes"
IsAgeWise : No
Periodicity : "3 Month"

560
Advanced Reporting and Printing

[Object: Exer CSS HalfYearly]


Name : $$LocaleString:"Half-Yearly"
VarName : "SVFromDate, SVToDate"
CollName : "Period Collection"
BelongsIf : "Yes"
IsAgeWise : No
Periodicity : "6 Month"

[Object: Exer CSS Monthly]


Name : $$LocaleString:"Monthly"
VarName : "SVFromDate, SVToDate"
CollName : "Period Collection"
BelongsIf : "Yes"
IsAgeWise : No
Periodicity : "Month"

[Object: Exer CSS Yearly]


Name : $$LocaleString:"Yearly"
VarName : "SVFromDate, SVToDate"
CollName : "Period Collection"
BelongsIf : "Yes"
IsAgeWise : No
Periodicity : "Year"

;; Report AutoColumn
[Report: Exer CSS AutoColumns]
Auto : Yes
Title : $$LocaleString:"Auto Repeat Columns"

[Form: Exer CSS AutoColumns]


No Confirm : Yes
Full Width : No
Space Top : 1
Space Bottom : 1

561
Advanced Reporting and Printing

Space Left : 1
Space Right : 1
Background : @@SV_UNYELLOW
Parts : Exer CSS AutoColumns
Output : Exer CSS AutoColumns
Option : Small Size Form
;; Output Attribute at Form Definition is used to return a Field value to the calling Report.
;;No Confirm Attribute at Form Definition will not prompt the user to save the auto-column screen

[Part: Exer CSS AutoColumns]


Lines : Form SubTitle, Exer CSS AutoColumns
Local : Field : Form SubTitle : Info : $$LocaleString:+
"Auto Repeat Columns"

[Line: Exer CSS AutoColumns]


Fields : Medium Prompt, Exer CSS SelectAuto, Exer CSS AutoColumns+
Fields : Exer CSS CollName, Exer CSS StartPeriod
Fields : Exer CSS EndPeriod, Exer CSS SetPeriodicity
Local : Field : Medium Prompt : Info : $$LocaleString:+
"Repeat Using :"
SpaceBottom : 0.25

[Field: Exer CSS SelectAuto]


Use : Short Name Field
Table : Exer CSS AutoColumns
Show Table : Always

[Field: Exer CSS AutoColumns]


Use : Short Name Field
Invisible : Yes
Set as : $$Table:ExerCSSSelectAuto:$VarName
Set always : Yes
Skip : Yes
/* Function Table selects the Object Name from the previous Field 'ExerCSSSelectAuto' and displays the corresponding
method value of VarName*/

562
Advanced Reporting and Printing

[Field: Exer CSS CollName]


Use : Short Name Field
Invisible : Yes
Set as : $$Table:ExerCSSSelectAuto:$CollName
Modifies : DSPRepeatCollection
Set always : Yes
Skip : Yes
/*We are modifying the value of the default variable DSPRepeatCollection by the value of the Method CollName from the
selected Object DSPRepeatCollection is repeated in the Default Variables SVCurrentCompanySVFromDate and
SVToDate, which gets new values for each column*/

[Field: Exer CSS StartPeriod]


Use : Short Date Field
Invisible: Yes
Set as : if $$IsEmpty:$$Table:ExerCSSSelectAuto:+
$Periodicity then ##SVFromDate else if+
$$Table:ExerCSSSelectAuto:$Periodicity =+
"Day" then ##SVFromDate else $$LowValue:+
SVFromDate
Set always : Yes
Modifies : SVFromDate
Skip : Yes
/* Value of Variable 'SVFromDate' is set here based on the Periodicity Method. LowValue is a Function that returns
beginning date of the Current Period*/

[Field: Exer CSS EndPeriod]


Use : Short Date Field
Invisible : Yes
Set as : if $$IsEmpty:$$Table:ExerCSSSelectAuto:+
$Periodicity then ##SVToDate else +
if $$Table:ExerCSSSelectAuto:$Periodicity = +
"Day" then $$MonthEnd:#DSPStartPeriod +
else $$HighValue:SVToDate
Set always : Yes

563
Advanced Reporting and Printing

Modifies : SVToDate
Skip : Yes
/* Value of Variable 'SVToDate' is set here based on the Periodicity Method. MonthEnd is a Function gives the last day for
a given month*/

[Field: Exer CSS SetPeriodicity]


Use : Short Name Field
Invisible : Yes
Set as : if NOT $$IsEmpty:$$Table:ExerCSSSelectAuto:+
$Periodicity then $$Table:ExerCSSSelectAuto:+
$Periodicity else "Month"
Set always : Yes
Modifies : SVPeriodicity
;; End-of-File
Output

In the Report Exer Columnar Stock Summary, Exer CSS MultiColumns used as Colmnar
Report which is invoked to accept the user inputs. These inputs provide values to the various
repeat variables over which a column/field is repeated.

564
Advanced Reporting and Printing

The system variables SVCurrentCompany, SVFromDate, and SVToDate are Repeated at


Report Exer Columnar Stock Summary by using attribute Repeat. In Report Exer CSS
MultiColumns based on user input SVCurrentCompany, SVFromDate, and SVToDate
variables are modified by using Field attribute Modifies.
In the Line Exer CSS Details, Field Exer CSS Qty is repeated. This is a compound Field and
has Exer CSS Open,Exer CSS Inwd, Exer CSS Outw and Exer CSS Clsg has sub fields.
The Form Exer Columnar Stock Summary is having a Button Exer CSS AutoButton,
through this Button, the Report Exer CSS AutoColumns is invoked for user intervention. In
this Button the Action Auto Columns is used bring system in auto column mode. In this
Report , the user can choose one of the option from ‘Days’,’ Monthly’, and ‘Yearly’ based on
which the columns are repeated. Based on any of these options selected the Collection name,
Variable name, and periodicity will be populated with values.
The Form attribute output with Field ‘Exer CSS AutoColumns’, will provide the values to
the variable, so that columns are repeated in the calling report.

Designing an Automatic Auto Column Report


This is an Auto column Report where the options are preset prior to the report invocation and
does not depend on the user intervention. i.e the Repeat variable and the collection to be used
from which this variable gets its values is preset at the report level.
The design of the main report is exactly the same as used in the other examples .The additional
specifications which are to be considered while creating the automatic auto-column reports are
as follows:
 The Repeat specification for the Report is done in the same way as in AutoColumn
report
 The variable DoSetAutoColumn needs to be declared at the report level and to be set
to Yes.
 The variable DSPRepeatCollection which stores the Collection Name is to be set at
the report level
 A dummy optional form has to be defined based on the value returned by the func-
tion $$SetAutoColumns which accepts the name of the repeat variable over which
the columns are repeated.
Example:
Consider the example of creating an auto-column for a Trial Balance where the columns to be
repeated for all active companies need to be preset by the programmer . At the report level the
variable “DoSetAutoColumn” is set to “Yes” and “DSPRepeatCollection” is set with the
value “List of Primary Companies”

565
Advanced Reporting and Printing

[Report: AutoCol Trial Balance]


Variable : DoSetAutoColumn
Set : DoSetAutoColumn : Yes
Set : DSPRepeatCollection: "List of Primary Companies"

An optional form Set Auto Option is added based on the value returned by the function
$$SetAutoColumns taking the variable name “SVCurrentCompany” as parameter. The report
repeats on the basis of no of values stored in this variable. In our example it is the list of active
companies.
[Form: AutoCol Trial Balance]
Option: Set Auto Option : $$SetAutoColumns:SVCurrentCompany

[!Form: Set Auto Option]

Figure 12.7 Trial Balance of two different loaded companies for a specific period

566
Advanced Reporting and Printing

Traditional Matrix Reports-Using the Auto Column approach


A matrix report looks like a grid. it contains a row of labels, a column of labels, and informa-
tion in a grid format that is related to both the row and column labels. In Tally, two dimen-
sional matrix reports can be designed using the auto column report approach.
Multidimensional matrix reports can be designed using the Field repeat approach which will
be discussed in the subsequent section.
A typical two dimensional matrix report showing the sales made by each salesman for each
month is shown as below:
Jan Feb Mar Apr May June
Salesman A $100 $160 $220 $180 $230 $150
Salesman B $120 $210 $250 $120 $180 $290
Salesman C $205 $170 $180 $240 $220 $110
In a traditional auto/automatic auto column reports the columns are repeated over a predefined
variable and the method values within the detail line is extracted based on the internal linking
with the variable. Matrix reports is a variant of auto/automatic auto column reports where the
columns are repeated over a variable which is defined by the programmer. The collection used
to populate the values into this variable is also defined by the programmer. The method values
in the detail line is extracted from a different collection based on corresponding row and
column values.

Example:
A report needs to be generated for displaying the Item Wise Party Wise Sales. The items are
displayed as title in rows and party names are displayed as titles across columns. The Billed
qty for each item to a particular party is displayed as information in the grid.

567
Advanced Reporting and Printing

The report CFBK Rep repeats the columns over the Repeat variable PName and sets the
value of the variable DoSetAutoColumn to yes and DSPRepeatCollection to CFBKParty.
[Report: CFBK Rep]
Variable: DoSetAutoColumn, PName
Repeat : PName
Set : DoSetAutoColumn : Yes
Set : DSPRepeatCollection : "CFBK Party"

Since the columns need to be preset before report invocation an optional form is added based
on the value returned by the function $$SetAutoColumn taking PName as the parameter.
[Form: CFBK Rep]
Option : Set Auto Vch Option : $$SetAutoColumns:PName

[!Form: Set Auto Vch Option]


The variable “PName” definition repeating over ##DSPRepeatCollection” is given below:

568
Advanced Reporting and Printing

[Variable: PName]
Type : String
Repeat : ##DSPRepeatCollection

The collection CFBKParty definition is given as below. This collection aggregates the
vouchers by Party ledger name and this is available in the collection with the method name
PName.The variable PName gets multiple values from the method PName of the collection
CFBK Party.
[Collection: CFBK Party]
Source Collection : CFBK Voucher
Walk : Ledger Entries
By : PName : $PartyLedgerName
Aggr Compute : Ptot: SUM: $Amount

The source collection used for this collection is defined as below


[Collection: CFBK Voucher]
Type : Voucher

The detail line “CFBK Rep Details” repeats over the collection “SMP Stock Item”
[Part: CFBK Rep]
Lines : CFBK Rep Title, CFBK Rep Details
BottomLines: CFBK Rep Total
Repeat : CFBK Rep Details: Smp Stock Item

Collection definition “SMP Stock Item” aggregates the vouchers by StockItemName which is
available in the collection with the method name “IName”
[Collection: Smp Stock Item]
Source Collection: CFBK Voucher
Walk : Inventory Entries
By : IName : $StockItemName
Aggr Compute : BilledQty: SUM: $BilledQty

569
Advanced Reporting and Printing

The line CFBK Rep Name contains the field CFBK Rep Name which displays the method
value IName. The field CFBK Rep Party is a repeated field.
[Line: CFBK Rep Details]
Fields : CFBK Rep Name, CFBK Rep Party, CFBK Rep Col Total
Repeat : CFBK Rep Party

The repeated field displays the value from a collection CFBKSummVoucher using the
function $$Collectionfieldbykey using the corresponding row and column field value as the
search key value.
[Field: CFBK Rep Party]
Use : Qty Primary Field
Set As : $$ReportObject:$$CollectionFieldByKey: +
$BilledQty:@MyFormula:CFBKSummVoucher
MyFormula: ##PName + #CFBKRepName
Format : "NoZero"
Border : Thin Left

The collection CFBK Rep Party aggregates the vouchers by PartyLedgerName and then by
StockItemName and calculates the sum of Billed Qty.The search key is defined which is a
combination of the PartyLedgerName and the StockItemName.When this collection is used
in the field CFBK Rep Party the value for the search key is provided by the corresponding
row and column title and the billedqty is accessed on the basis of that.
[Collection: CFBK Summ Voucher]
Source Collection: CFBK Voucher
Walk : Inventory Entries
By : PName : $PartyLedgerName
By : IName : $StockItemName
Aggr Compute : BilledQty: SUM : $BilledQty
Search Key : $PName + $IName

12.2 Printing
Printing is the most powerful aspect of Tally. Any report which is available as a part of the
application can just be printed on the click of a button. Moreover, this is completely configura-

570
Advanced Reporting and Printing

ble from the end users point of view. The various configuration setting help the user in
achieving the following:
 The user can render the report to any output printer which is available as a part of
windows environment. i.e it is possible to direct the output to a Pdf writer, Snagit,
Fax machine etc. This enables saving the output in multiples formats as desired.
 Various modes of printing available facilitate printing as per the mode selected ie
Neat, Dot Matrix & Draft mode
 Printing can be configured as per the stationary available whether it preprinted/plain,
paper type, size etc.

By default Tally.ERP9 retrieves the recent printing configuration which can be from the
default printer settings or the last configuration specified in Tally.ERP9 application. The
default configuration screen is displayed as below:
From the programmer’s point of view, enabling printing for any report which is customized is
merely the task of adding the print button to the form. In addition to it, the various actions,
attributes and events for printing and configuration setting provide enormous control and flex-
ibility in the hands of the programmer for handling various requirements. These capabilities

571
Advanced Reporting and Printing

allow printing the same report in multiple formats, Invoice Printing, Multi-account printing,
Index page printing, providing horizontal/vertical page breaks, to name a few.

Tips for Printing


 By default, the report that is currently open will be printed on executing the print
action.
 The printing of the output depends on the printer or the paper and cannot be control-
led by TDL.
 In TDL, a form smaller than the size of the paper can be printed, but a form larger
than the size of the paper cannot be printed.

The printing capabilities in TDL are quite an exhaustive which is covered in detail in this
chapter. Let’s begin with the understanding of printing modes in Tally.ERP9.
12.2.1 Modes of Printing / Printing Formats
The user can specify the printing mode as per his requirement. The various print formats
available in Tally.ERP 9 are Dot matrix format, Neat mode and Quick/ Draft mode. The user
can change the print format by clicking on the button Print Format and then selecting the
format based on requirement.
Dot Matrix Format allows printing Tally.ERP 9 reports in text format using the dot matrix
printers. Dot Matrix mode is compatible with dot matrix printers. It is important to note that
only Epson printer drivers (LQ and FX series) can be used on selecting this format.
The default format for printing any report is Neat Mode. All the reports can be printed in
Quick/Draft mode except for cheques. The Neat mode and Quick/ Draft modes are compatible
with most of the printer drivers installed on the Windows Operating System.

The selected reports are available for preview only when the selected format is
Neat Mode

12.2.2 Report Printing / Printing Techniques


Printing can be initiated by launching the action Print directly from the Menu, TDL procedure,
Key/Button. As soon as the print action is executed, the system prompts the user for confirma-
tion with the Print Configuration report. The default configuration report ‘SV Print Configura-
tion’ is used to specify the print settings like printer mode, paper size etc. as explained earlier
and click on enter. The specified is report is printed as per the print configuration setting.

572
Advanced Reporting and Printing

In the succeeding section we will discuss the various techniques available with respect to
printing which allows us to effectively deliver the various printing capabilities
 Printing the Current Report using default “Print Button”
 Using Action “Print”, “Print Report” and “Print Collection”
 Print Configuration using “Print” Attribute of the Report
 Suppressing Configuration for the above Actions
 Printing Single/Multiple Forms using “Print” Attribute of the Form
 Multi Account Printing using “Collection” attribute of Report

Let us start understanding each technique in depth and the required attributes.

Printing the Current Report using default “Print Button”


The simplest way to print a report is to attach the predefined button ‘Print Button’ at form
level. The current report is printed whenever the user clicks on the Print button or presses Alt
+ P.
Example:
[Report: MyTrialBalance]
Form: MyTrialBalance

[Form: MyTrialBalance]
Top Part : Title Part
Part : Main body
Bottom Part: Total Part
Button : Print Button
The report ‘My Trial Balance’ is printed by pressing the Print button available on the Top
button bar. The print button triggers the Action Print Report which prints the report Trial
Balance in the same format in which is displayed. The default configuration screen is automat-
ically launched whenever this action Print Report is invoked.The Print Button is defined in
Default TDL as given below:
[Key: PrintButton]
Key : Alt+P
Title : $$LocaleString:"Print"
Type : PrintButton
Action : Print Report

573
Advanced Reporting and Printing

Using Action “Print”, “Print Report” and “Print Collection”


The various action provided by TDL for report printing are ‘Print’, ‘Print Report’ and ‘Print
Collection’.

Using Action – Print


The action Print can be invoked directly from Menu, Button/Key or from a TDL Function. It
prints the specified report based on the print configuration settings.

Syntax:
Print : <Report Name> [ :<Logical Value>]
Where,
<Report Name> is the name of report to be printed.
<Logical Value> can be TRUE, FALSE, and YES or NO. This value can be used to skip the
display of configuration setting if value of the required parameter is set.

The omission of the configuration report is discussed separately in the section


“Programmable Configuration for the Print action”.

Example:
[#Menu: Printing Menu]
Add : Key Item: My Day Book: D : Print: Day Book
In the above example, a menu item ‘My Day Book’ is added. On selection it prints the report
‘Daybook’. On accepting the print configuration screen, the report is printed.

Using Action – Print Report


Another method of printing the reports is by associating a Button with an action Print Report
at the Form definition. The action Print Report accepts report name as parameter and prints the
same. If the report name is not specified then it prints the current report by default.

Syntax
[Button: <Button Name>]
Action : Print Report [: <Report Name>]

574
Advanced Reporting and Printing

Where,
<Report Name> is a report name to be printed by using the action Print Report. This is an
optional parameter. In the absence of Report Name by default the current report is printed.

Example:
[Button: Print Selected Pay slips]
Key : Alt + F11
Title : "Print Selected Pay slips"
Action: Print Report : Multi Pay Slip Print

Using Action – Print Collection


The Action Print Collection is used to print the report corresponding to an existing Object of
Collection thus specified. The Collection definition specifies the Report to be printed ie the
Report specified with the Report Attribute of the Collection is printed. The Object is to be
selected from a different Report. This is specified by using the attribute “Trigger” of the col-
lection. This action is similar to Alter and Display collection as discussed in previous chapters.

Example:
;; Menu definition specifying the Action “PrintCollection”

[Menu: Print Ledger]


Key Item : “Vouchers of Ledger” : O : Print Collection : +
Monthly Ledger Extract
;;Collection definition specifying the Trigger Report and the Report to be printed as per Object selected

[Collection: Monthly Ledger Extract]


Type : Ledger
Variable : Ledger Name
Report : Ledger Vouchers
Trigger : Led List
Fetch : Name
When the user selects the option “Vouchers of Ledger” from the menu, the trigger report ‘Led
List’ is displayed with a list of Ledger Names. Based on the user selection the report ‘Ledger
Vouchers’ is printed which is a list of Vouchers corresponding to the selected Ledger.

575
Advanced Reporting and Printing

Print Configuration using “Print” attribute of the Report


As explained earlier, the default configuration report is displayed when the user clicks on the
Print button or presses ALT+P. Tally.ERP9 uses separate configuration reports for printing the
Trial Balance, Day Book, Cheque Printing etc. These configuration reports are specified at the
Report Level using the attribute Print. If this attribute is not used at the Report level, then the
print configuration screen will be displayed without additional configuration details.
The default configuration report ‘SVPrintConfiguration’ is invoked only when the Report
specified does not contain the Print attribute in its own definition. The Print attribute allows
the user to specify his own configuration settings whenever any of the print action is invoked.

Syntax
[Report : <Report Name>]
Print : <Report Name>
Where,
<Report Name> is a name of the configuration report to be displayed.

Example:
[Report: My Trial Balance]
Form : My Trial Balance Form
Print : TB Print Configure

When the user clicks on the Print button or presses ALT+P to print the report ‘My Trial
Balance’, the configuration report ‘TB Print Configure’ is displayed. The user must accept the
configuration screen to print the report. The report ‘TB Print Configure’ is a predefined report
in Tally for printing ‘Trial Balance’ report.

Programmable Configuration for the Print action


As explained earlier, whenever the action Print is executed, a configuration report ‘SVPrint-
Configuration’ is displayed. The user provides the details in the configuration screen based on
the action being executed. The action gets executed based on the values provided in the con-
figuration. These parameters are persisted as system variable so that next time these can be
considered as default settings.
For successful execution of these actions along with the report name, additional action specific
parameters like Printer Name, Paper Type, No. of Copies to be printed etc. are also required.
These action specific parameters are passed by setting the value of variables through configu-
ration report – ‘SVPrintConfiguration’.

576
Advanced Reporting and Printing

There are situations when multiple reports are being printed in a sequence. Subsequent to each
Print action, if a configuration report is popped up for user input, this interrupts the flow,
thereby requiring a dedicated person to monitor the process which is time consuming too. The
configuration report can be suppressed by specifying a logical parameter. Since the configura-
tion report is suppressed, the value of the various variables used by Print action must be set to
required values.
Following section explains the print action specific variables and their acceptable values.

Variables Specific to action – Print


As soon as the user executes a Print action following screen is displayed:

This screen captures the user input such as the “Printer Name”, “No. of Copies” to be printed
etc. The various action specific variables required by the Print action are modified based on
the user input. Following variables are used by Print action:

SVOutputType
The value of this variable is one of the predefined button type keywords like ‘Print Button’,
‘Export Button’, ‘Upload Button’, ‘Mail Button’. The variables value is used by the functions
$$InMailAction, $$InPrintAction, $$InUploadAction and $$InExportAction to determine the
execution of correct option in the form ‘SVPrintConfiguration’.

For eg, if the value of ‘SVOutputType’ is ‘Print Button’ then the optional form ‘SV Print-
Config’ in the report ‘SVPrintConfiguration’ is executed.

SVPrintMode
This variable is used by Print action and accepts printing mode as value. The Print mode can
be “Neat”, “DMP” or “Draft” which are system names. The default mode is Neat mode.

SVPrintFileName
This variable is applicable for Print action, only if “PrintToFile” option is selected by the user
while printing in DOT Matrix or Quick / Draft format. In this case the variable ‘SVPrint-

577
Advanced Reporting and Printing

FileName’ accepts the filename by using the function $$MakeExportName function to add
right extensions.

SVPrintToFile
This is a logical value which determines if the print output should be saved in a file and is
applicable only for DMP or Draft mode. If the value is TRUE the output is saved in the file
specified in the variable ‘SVPrintFileName’. If the vale is FALSE then the variable
‘SVPrinterName’ must contain a valid printer name.

110: SET: SVPrintFileName:$$MakeExportName:##LedgerName: +


##SVExportFormat
SVPrinterName
It accepts a printer name as a value for printing and the same will be retained for future use.
When no printer is selected in Tally.ERP9 then the default value is taken from the system
settings available in Control Panel for Printers and Faxes.

SVPreview
This is a logical variable and is applicable only for Print action with neat mode format. If the
value is set to Yes then preview of the report is displayed. Otherwise the report is printed
without displaying the preview.

[Button: Change Preview]


Key : Alt+I
Action : Set : SVPreview : NOT ##SVPreview
Title : if ##SVPreview then + $$LocaleString:"No Preview" else +
$$LocaleString:"With Preview"

SVPrintCopies
The variable is applicable only for Print action. It accepts a number to print multiple copies.

SVPrePrinted
The variable is applicable only for Print action and it specifies whether a pre-printed stationary
or plain paper is to be used for printing.

578
Advanced Reporting and Printing

SVPrintRange
The variable is applicable only for Print action. This variable determines the range of pages to
be printed.

SV Draft Split Names


It accepts a logical value to determine if the long names should be split into multiple lines.
This variable is not applicable for Neat mode.

SV Draft Split Numbers


It accepts a logical value to determine if the long numbers should be split into multiple lines.

SVPrintStartPageNo
The variable is applicable only for Print action. This variable allows to specify the starting
page number.

SVPosMode
It determines if POS mode to be used. The default value of this variable is No.

Example:
[#Menu: Gateway of Tally]
Add : Key Item : Before : @@locQuit : Print Balance Sheet : N : +
CALL : Suppress Balance Sheet Config

[Function: Suppress Balance Sheet Config]

Variable: SV PrinterName: String


Variable: SV Preview, SV PrePrinted: Logical

00: SET: SV PrinterName: "Adobe PDF"


10: SET: SV Preview: Yes
20: SET: SV PrePrinted: Yes
30: PRINT: Balance Sheet: TRUE

579
Advanced Reporting and Printing

When the user selects the menu item “Print Balance Sheet”, the function “Suppress Balance
Sheet Config” is called to print the report “Balance Sheet” without displaying the print config-
uration report.
The values for the required variables are set in the function. In case the values are not set
explicitly then by default the values of these variables are set based on the previous print con-
figuration setting.

Printing Single/Multiple Forms using “Print” Attribute of the Form


As mentioned earlier, Tally.ERP9 allows printing a report in multiple formats e.g. like Receipt
voucher and Formal receipt printing or cheque printing. Printing of multiple report formats is
enabled by using the Print attribute of Form definition. The attribute Print is used for adding
multiple report formats along with the current form.
The Print attribute of the definition Form is used to attach more reports to the existing report.
E.g. In the Tally.ERP9 application Report Printed invoice has a form named Sales Color in
which many reports can be added. The attribute ‘Print’ is a Single List attribute.

Syntax
Print : <Report Name>
Where,
<Report Name> is the name of the report to be printed along with the current report.

Example:
Consider the scenario where a customer purchases goods and wants a label printed for each of
the items purchased.

[#Form : Sales Color]


Add: Print : EI LabelPrinting

The attribute Print is used in the form ‘Sales Color’ to print the additional report ‘EI Label-
Printing’ along with the default report ‘Sales Color’.

580
Advanced Reporting and Printing

When we click on print button the default print report is displayed.

Figure 12.8 Default Print Report

The above figure shows the Items entered in the Invoice. When the user selects Escape key
then the print configuration report is displayed as follows:

581
Advanced Reporting and Printing

Figure 12.9 Configuration screen for printing label report

On pressing ‘Yes’ in the figure given below, the label report is displayed as shown:

The above figure shows the labels printed based on the quantity of stock item.

Multi-Account Printing using “Collection” attribute of Report


The Tally.ERP9 feature, Multi-Account printing is used to print the primary books of accounts
like the Cash and Bank Books, Account Ledgers, Sales and Purchase Registers instead of
selecting the accounts one at a time and pressing ALT+P. This facilitates to print one account
at a time, all accounts or all accounts in a selected group. Before printing, the date range and
other selections can also be set up.
The Report attribute “Collection” is used to facilitate the multi-account printing capability.
The collection name is the name of primary collection on which the report is repeated. The
report is printed for each object of the collection.
Syntax
[Report : <Report Name>
Collection : <Collection Name>, <Variable Name> : <Condition>

582
Advanced Reporting and Printing

Where,
<Report Name> is the name of the report to be used form multi-account printing
<Collection Name> is the name of collection on which the report will repeat. The optional
<Variable Name> can be passed here which will inherit object name in the variable and
further the variable can be used in the report.
<Condition> can be any expression which when evaluated to True then only the report is
repeated over the specified collection.

Example:
Consider the following example to print all the vouchers of a Ledger. The logical variable
##InNewPages specifies whether to print the report for a particular ledger in a new page.

[Report: TSPL Multi Ledger Printing]


Collection : TSPL ML Ledger Coll, Ledger Name : ##InNewPages

The report “TSPL Multi Ledger Printing” is repeated on the collection “TSPL ML Ledger
Coll” if the value of the variable “InNewPages” is True. The variable “Ledger Name” is the
variable which holds the Name of the current object of collection “TSPL ML Ledger Coll”.

12.2.3 Page breaks


The Page Break is the point at which one page ends and another begins. Handling Page Breaks
is very important since the current page should indicate the continuation to the next page and
the next page must indicate that the current page is continued from a previous page. This
indicates that there has to be a closing identifier i.e., closing page break information and an
opening identifier i.e., opening page break information.
In other words, Page Breaks specifies the headers and footers for every page when the printing
spans across multiple pages. Closing Page Break starts printing from the first page and prints
on every page except the last page. For e.g., Continued... to be printed at the bottom of each
page. Opening Page Break starts printing from the second page till the last page. Closing
Page Break is specified before Opening Page Break since in any circumstance, closing page
break will be encountered first.
In case of columnar reports, the entire width of the report cannot be accommodated in a single
page. In cases like this when the reports spans across multiple pages horizontally, horizontal
page breaks are required i.e., pagebreaks are to be printed on the right and left of the page.

583
Advanced Reporting and Printing

Vertical Page breaks


When a report containing the data that cannot be printed in a single page, one needs to use
vertical page breaks. Vertical Page Breaks can be specified at Form and Part level.

Form level Page Break


Vertical Page Breaks can be specified at Form through the Form attribute “Page Break”. It
takes two part names as parameters, viz., First Part for Closing Page Break and Second Part
for Opening Page Break.

Syntax
[Form: <Form Name>]
Page Break : <Closing Part>, <Opening Part>
Where,
<Closing Part> and <Opening Part> are the names of part to be used at the end and
beginning of a page

Example:
Consider a Trial Balance report of a company, where we may require the title and the address
of the company in the first page and the grand total in the last page. In pages between first and
last page, we may require the text continued at the end of each page and Company Name &
Address at the beginning of each page.

[Form: My Trial Balance]


Page Break : Cl Page Break, Op Page Break

584
Advanced Reporting and Printing

[Part: Cl Page Break]


Lines : Cont Line

[Line: Cont Line]


Fields : Cont Field
Border : Full Thin Top

[Field: Cont Field]


Set As : “Continued…..”
Full width : Yes
Align : Right

[Part: Op Page Break]


Parts : DSP OpCompanyName, DSP OpReportTitle
Vertical : Yes

In the above example, Closing Page Break is defined to print Continued at end of every
continued page. Opening Page Break is defined to print Company Name and Report Title at
beginning of all continuing pages. Since more than one part is used within part definition, the
alignment if Vertical needs to be specified.

Part level Page Breaks


Vertical Page Breaks can be specified at Part through the Part Attribute “Page Break”. This is
generally used if Page Totals are to be printed for each closing and opening pages.
It takes two line names as parameters, viz., First Line for Closing Page Break and Second Line
for Opening Page Break.

Syntax
[Part: <Part Name>]
Page Break : <Closing Line>, <Opening Line>
Where,
<Closing Line> and <Opening Line> are the names of Lines to be used at the end and
beginning of a page.

585
Advanced Reporting and Printing

Example:
Consider a Trial Balance report of a company, where we may require the running page totals to
be printed at the end and beginning of each page.
[Part: My Trial Balance]
Page Break : Cl Page Break, Op Page Break

[Line: Cl Page Break]


Use : Detail Line
Local : Field : Particulars Fld : Set As: “Carried Forward”
Local : Field : DrAmt Fld : Set As : $$Total:DrAmtFld
Local : Field : CrAmt Fld : Set As : $$Total:CrAmtFld
Local : Field : NetAmt Fld : Set As : $$Total:NetAmtFld
Border: Full Thin Top

[Line: Op Page Break]


Use : Cl Page Break
Local: Field : Particulars Fld : Set As : “Brought Forward”

In the above example, Line “Cl Page Break” is defined to use the pre-defined “Detail Line”
and the relevant fields are modified locally to set the respective values. Similarly, line “Op
Page Break” is defined to use the above defined line “Cl Page Break” which locally modifies
only the particulars field.

Horizontal Page breaks


Horizontal page breaks are similar to vertical page breaks. If the printable report is wider than
the physical width of the paper, it is necessary to have the text Carried Over and Brought
Forward to be displayed at the required locations. In such cases, page breaks are defined in
‘Line’. The fields to be displayed on each page can be marked as fixed using the field attribute
‘Fixed’. All the fields marked as Fixed will appear in all pages.
Horizontal Page Breaks are used if number of columns run into multiple pages.

Line level Page Breaks


Horizontal Page Breaks can be specified at Line through the Line attribute “Page Break”. This
is generally used to repeat a closing column at every closing page and opening columns at
every opening page.

586
Advanced Reporting and Printing

It takes two field names as parameters, viz., first field for Closing Page Break and second field
for Opening Page Break.
The following figure depicts the location of the closing and opening page breaks.

Syntax
[Line: <Line Name>]
Page Break : <Closing Field>, <Opening Field>
Where,
<Closing Field> and <Opening Field> are the names of fields to be used at the end and
beginning of a page.

Example:
Consider a Columnar Sales Register report of a company, where multiple columns are being
printed running across the pages where we require some fixed columns in subsequent pages
which make it easy to map the columns in subsequent pages.
[#Line: DSP ColVchDetail]
Page Break : Cl Page Break, Op Page Break

[Field: Cl Page Break]


[Field : Op Page Break]
Fields : DBC Fixed, VCH No
In the above example, field Cl Page Break is defined as Empty as no Closing Column or field
is required and field “Op Page Break” is defined with further fields DBC Fixed and VCH No
which are available in default TDL.

587
Advanced Reporting and Printing

The following table summarizes the properties of the Page break at each level:
Form Level Page Break Part Level Page Break Line Level Page Break
It’s a Vertical Page Break It’s a Vertical Page Break It’s a Horizontal Page
Break
Page Break attribute Page Break attribute Page Break attribute
accepts Part Names as its accepts Line Names as its accepts Field Names as
value value its value

Multiple Parts (parts Multiple lines (lines Multiple Fields (Fields


within parts) can be within lines) can be within Fields) can be
printed both at closing printed at both closing and printed at both closing
and opening page breaks opening page break and opening page break
Form Level Page Breaks Running Page Totals can Column Page Totals can
cannot handle running be handled with Part be handled with Line
Page Totals Level Page Break Level Page Break
Exercise 12.3
Objective
The objective of this program is to understand the steps involved in customizing an
Sales Invoice for printing.

Capabilities Used
 The procedural capability of TDL is used to calculate the Nth Power of a Number.
 The field attribute Print is used in form “Sales Color” to print the Invoice user
defined format instead of default format.
 The attribute Page Break is used at form level to print the closing and opening page
break.

588
Advanced Reporting and Printing

Code
[Report: Exer Sales Invoice Cust]
Use : Daybook
Local : Line: DB Title : Local : Field : Name Field : Set As :"List +
of Sales Invoices- Select a Sales Invoice required to be+
printed"
Local : Collection : Default: Add : Filter: Exer Sales Invoices
Title : "Sales Invoice Customization and Printing"

[System: Formula]
Exer Sales Invoices: $$IsSales:$VoucherTypeName
;; Sales Invoice Customization

[#Form: Sales Color]


Delete: Print ;; Deleting the default Print and adding new Report to be printed
Add : Print: Exer Sales Inv Cust

[Report: Exer Sales Inv Cust] ;; Sales Invoice Report to be printed


Form : Exer Sales Inv Cust
PrintSet: ReportTitle: "Customized Sales Invoice"
;; Current Object Voucher is associated with the Report
Object : Voucher

[Form: Exer Sales Inv Cust]


Use : STDInvoiceDimensions
/* Default Part 'STDInvoiceTop' is used here which removes the Party Name (by storing the first line item) from the
Object 'Ledger Entries' and making it invisible as a result of which, when lines repeat over LedgerEntries, Party Name
does not get printed along with discounts and taxes.*/
Parts : STDInvoiceTop, Exer Sales Inv OpPgBrk, Exer Sales Inv Details
BottomParts: Exer Sales Inv Totals
;; Closing and Opening Parts used as Form Page Breaks
Page Break : EXPINV PageBreak, Exer Sales Inv OpPgBrk
/*Opening Page Break gets printed on all the Pages except the First Page and Closing Page Break gets printed on all the
pages except the Last Page*/

589
Advanced Reporting and Printing

[Part: Exer Sales Inv OpPgBrk]


;; Default Parts for the initial Company & Party Details along with Title
Parts : DSP VoucherTime, EXPINV Jurisdiction, EXPSMP Copy, +
EXPSMP Company, EXPSMP InvTitle, EXPSMP Party, +
Exer Sales Inv ColumnTitle
Vertical: Yes

[Part: Exer Sales Inv ColumnTitle]


Lines: Exer Sales Inv ColumnTitle

[Line: Exer Sales Inv ColumnTitle]


Fields : Exer Sales Inv SlNo, Exer Sales Inv Particulars
Right Fields: Exer Sales Inv Qty, Exer Sales Inv Rate, +
Exer Sales Inv Amt
Local: Field: Default: Style: Normal Bold
Local: Field: Default: Type : String
Local: Field: Default: Align: Centre
Local: Field: Exer Sales Inv SlNo : Set As: "Sl No."
Local: Field: Exer Sales Inv Particulars : Set As: "Particulars"
Local: Field: Exer Sales Inv Qty : Set As: "Qty"
Local: Field: Exer Sales Inv Rate : Set As: "Rate"
Local: Field: Exer Sales Inv Amt : Set As: "Amount"
Border: Thin Top Bottom

[Part: Exer Sales Inv Details]


Parts : Exer Sales Inv InvDetails, Exer Sales Inv AccDetails
Vertical : Yes
Common Border: Yes
Scroll : Vertical

[Part: Exer Sales Inv InvDetails]


Lines: Exer Sales Inv Info, Exer Sales Inv SubTotal
;; Line 'Exer Sales Inv SubTotal' is repeated over the sub object 'Inventory Entries'
Repeat: Exer Sales Inv Info: Inventory Entries

590
Advanced Reporting and Printing

[Line: Exer Sales Inv Info]


Fields: Exer Sales Inv SlNo, Exer Sales Inv Particulars
Right Fields: Exer Sales Inv Qty, Exer Sales Inv Rate, +
Exer Sales Inv Amt
Local: Field: Default: Style: Normal

[Field: Exer Sales Inv SlNo]

[Field: Exer Sales Inv SlNo]


;; When lines are repeated over a Collection, $$Line returns the current repeated line number
Set As : $$Line
Width : 5

[Field: Exer Sales Inv Particulars]


Use : Name Field
Set As : $StockItemName
FullWidth : Yes
Border : Thin Left

[Field: Exer Sales Inv Qty]


Use : Qty Primary Field
Set As : $BilledQty
Border : Thin Left

[Field: Exer Sales Inv Rate]


Use : Rate Field
Set As : $Rate
Border : Thin Left
Width : 15% Page

[Field: Exer Sales Inv Amt]


Use : Amount Forex Field
Set As: $Amount
Border: Thin Left

591
Advanced Reporting and Printing

[Line: Exer Sales Inv SubTotal]


Fields : Exer Sales Inv SlNo, Exer Sales Inv Particulars
Right Fields: Exer Sales Inv Qty, Exer Sales Inv Rate, +
Exer Sales Inv Amt
Local: Field: Default : Style: Normal Bold
Local: Field: Exer Sales Inv SlNo: Set As: ""
Local: Field: Exer Sales Inv Particulars:Set As: "SubTotal"
Local: Field: Exer Sales Inv Qty: Set As: +
$$CollQtyTotal:InventoryEntries:$BilledQty
Local: Field: Exer Sales Inv Qty: Border: Thin Top
Local: Field: Exer Sales Inv Amt: Set As: +
$$CollAmtTotal:InventoryEntries:$Amount
Local: Field: Exer Sales Inv Amt: Border: Thin Top
Space Top: 0.25

[Part: Exer Sales Inv AccDetails]


Lines : Exer Sales Inv Info
Repeat : Exer Sales Inv Info: Ledger Entries
SpaceTop: 0.5
Local: Field: Exer Sales Inv SlNo : Set As: ""
Local: Field: Exer Sales Inv Particulars : Set As: $LedgerName
Local: Field: Exer Sales Inv Particulars : Align : Right
Local: Field: Exer Sales Inv Qty : Set As: ""
Local: Field: Exer Sales Inv Rate : Set As: ""

[Part: Exer Sales Inv Totals]


Parts : Exer Sales Inv TotalFigs, Exer Sales Inv TotalWords
Vertical: Yes

592
Advanced Reporting and Printing

[Part: Exer Sales Inv TotalFigs]


Lines: Exer Sales Inv Totals

[Line: Exer Sales Inv Totals]


Fields : Exer Sales Inv SlNo, Exer Sales Inv Particulars
Right Fields: Exer Sales Inv Qty, Exer Sales Inv Rate, +
Exer Sales Inv Amt
Local : Field: Default: Style : Normal Bold
Local : Field: Exer Sales Inv SlNo : Set As: ""
Local : Field: Exer Sales Inv Particulars : Set As: "Total"
Local : Field: Exer Sales Inv Qty: Set As : +
$$CollQtyTotal:InventoryEntries:$BilledQty
Local : Field: Exer Sales Inv Amt: Set As: $Amount
Border: Totals

[Part: Exer Sales Inv TotalWords]


Lines: Exer Sales Inv TotalWords

[Line: Exer Sales Inv TotalWords]


Fields: Simple Field, Exer Sales Inv TotalWords
Local: Field: Simple Field : Set As : "Amount in Words :"

[Field: Exer Sales Inv TotalWords]


Use : Name Field
;; Function 'InWords' converts its parameter i.e., Number or Amount into words
Set As: $$InWords:$Amount + " Only"
Width : 80% Page
;; End-of-File

593
Advanced Reporting and Printing

Output

Figure 12.10 Print Configuration Screen

594
Advanced Reporting and Printing

Figure 12.11 Invoice Format

Program Explanation
The form Sales Color is modified to Print the invoice in user defined format instead of the
default Tally.ERP9 format.
The attribute Print is used at form level to print the report Exer Sales Inv Cust which is
nothing but the user defined invoice format. In the report Exer Sales Inv Cust Object
Voucher is associated. The attribute PrintSet is used in report definition to set the value to the
variable Report Title to Customized Sales Invoice in print mode only.
In the part Exer Sales Inv InvDetails the line Exer Sales Inv SubTotal is repeated over the
sub object Inventory Entries.
The attribute Page Break is used to print Closing and Opening Parts used as Form Page
Breaks. The part EXPINV PageBreak is used as closing page break whereas part Exer Sales
Inv OpPgBrk is used as closing. Opening Page Break gets printed on all the Pages except the
First Page and Closing Page Break gets printed on all the Pages except the Last Page.

595
Advanced Reporting and Printing

When the user selects Print, the Print screen is displayed as shown in Fig. 12:10. Once the user
select Yes, the Invoice is printed in the user defined format as shown in Fig. 12:11.

12.2.4 Multi Page/Part Printing


The printing of a report which spans across multiple pages vertically i.e. when the line is
repeated, it is referred as Multi Page Printing. On the other hand, printing of a report spanning
across multiple pages horizontally i.e. when the column is repeated is referred as Multi Part
Printing. The Multi-Part Printing is basically used in columnar reports.
Consider the following report which spans across multiple pages vertically and horizontally:

Assume that only four columns can be printed on one page so Tally.ERP9 will print the above
reports as follows:

596
Advanced Reporting and Printing

597
Advanced Reporting and Printing

Each page is printed in three Parts and are named as Page 1(A), Page 1 (B), Page 1 (C) and
Page 2(A), Page 2 (B), Page 2 (C) respectively.
The predefined system variables “SVStartPageNo” and “SVPrintRange” are used for multi-
page/part printing. In the variable “SVPrintRange”, if the page numbers are specified as range
then the selected pages are printed and if the part numbers are specified as range then the
selected parts are printed. The validation and the implementation of printing the specified
pages/parts is handled by the platform itself.
Additionaly the function $$PageNo and $$PartNo are used in the reports to display the page
number and part number respectively.

598
Advanced Reporting and Printing

The printing sequence is as follows:

So if the part range is specified as 2A – 3C then the parts that are printed are Page 2 (A), Page
3 (A), Page 1 (B), Page 2 (B) and Page 3 (C).
Example:
Consider the following example where the report ‘Trial Balance’ is printed based on the page
range specified by the user.

[Report: MP Trial Balance]


Form : MP Trial Balance
Print : MP Set Page Range
Variable: SVStartPageNo, SVPrintRange
|
[Field: MP Trial Balance PgNo]
Use : Name Field
Set As: "Page " + $$String:$$PageNo
Align : Right

[Report: MP Set Page Range]


Auto : Yes
Title : $$LocaleString:"Set Page Range"

599
Advanced Reporting and Printing

[Field: MP PCFG StartPageNo]


Use : Number Field
Modifies: SVStartPageNo
Validate: $$Value > 0

[Field: MP PCFG PageRange]


Use : Name Field
Modifies: SVPrintRange
Validate: $$PageRangeOk:$$Value
In the above code snippet, the system defined variables ‘SVStartPageNo’ and ‘SVPrintRange’
are associated at report level. The report ‘MP Set Page Range’ is used to display the report to
accept the page range as user input. The Function 'PageNo' returns the page number of the
current page being printed.

12.2.5 Printing on a Pre Printed Stationary


In the previous sections, the different printing modes and printing techniques explained in
depth. This section explains another dimension of printing in Tally.ERP9.The reports can be
printed on the Pre-Printed stationary as well.
Most of the organization issue invoices on the preprinted stationary which carries the
Company name and address, Company Logo, terms and conditions etc. To print the reports on
preprinted stationary TDL provides various attributes like Pre-Printed and Pre-Printed Border
which when applied to a particular part/line/field will disable the content in print mode.
Let’s understand the usage of each attribute.

Preprinted/ Preprinted Border


The attribute “PrePrinted” or “PrePrinted Border” can be specified at Part, Line and Field Def-
initions. These attribute work in conjunction with preprinted/ plain button in the print config-
uration screen. When “PrePrinted” attribute is set to Yes, the contents of the current Part, Line
or Field will be left blank assuming the same to be pre-printed. When “PrePrinted Border”
attribute is set to Yes, the borders used in the current Part, Line or Field will be assumed to be
pre-printed.
Ideally, Preprinted is used where static texts are assumed to be preprinted like Invoice printing,
where Company Name, Address, static declaration, etc. are preprinted.

600
Advanced Reporting and Printing

Syntax
Pre Printed : Yes
12.2.6 Printing related Events – Before Print/After Print
We have already covered in previous chapters that an action can be triggered based on an
implicit event. There may be scenarios where some actions need to be invoked when a report
is being printed.
The attribute On along with event keywords events ‘After Print’ and ‘Before Print’ can be
used to handle printing related events. ‘On’ attribute can be specified for the definitions
Report, Form, Part, Line and Field. The event Before Print can be specified only at Report
level whereas the event After Print can be specified at Report, Form, Part and Line level.

Event – Before Print


The event Before Print is specific to Report object so it can be specified only within Report
definition. The event Before Print is triggered when the user executes Print action. The action
associated with the event is executed before the report is printed.
A list of actions can be executed before printing the report based on some condition.

Example:
[Report : Test Report]
On : BEFORE PRINT : Yes :CALL: BeforeRepPrint
The function ‘BeforeRepPrint’ is executed first and then the report ‘Test Report’ is printed.

Event– After Print


The event After Print can be specified for Report, Form, Part and Line definition. The event
After Print first prints the current interface object and then executes the specified actions asso-
ciated with this event.

Example:
[Line : LV AccTitle]
On : After Print: Yes : CALL : SetIndexLV:#LedgerName
The function ‘SetIndexLV’ is called after printing the line ‘LV AccTitle’. So if there are 10
lines to be printed, the function will be called ten times.

601
Advanced Reporting and Printing

12.2.7 Image Printing


The Tally.ERP9 application allows to print graphs and images along with the reports. The
attributes that supports image printing are Graph Type, Graph Label and Graph Value at field
and part level.
This section explains in detail the essentials of :
 Printing Image and
 Printing a Graph

Printing Image
The image printing capability can be used in various business scenarios like Logo Printing in
Sales Invoices, Stock Items Printing with their Images and many more. The attribute Graph
Type of Part definition is used to print the image.

Syntax
[Part: <Part Name>]
Graph Type: <path\File name>
Where,
<Part Name> is the name of the part which contains the image. This part cannot be used to
display or print any other content. Any content is specified at Line/ field level is ignored but an
empty field is mandatory. Appropriate dimensions i.e. Part Height and Width must be
specified to print the image within this Part.
<Path\FileName> is the location and name of the image file to be printed. At present the
image format supported are JPEG and BMP only.

Example:
[Part: Image Part]
Lines : Dummy Line
Graph Type: “C:\Images\ImageFile.BMP”

[Line: Dummy Line]


Fields: Simple Field
The part Image Part renders the specified image from the file ImageFile.bmp.

602
Advanced Reporting and Printing

Printing Graph
There are scenarios where the user requires a graph to be printed along with the report. The
Tally.ERP9 application allows to print Bar graphs only. The attributes Graph Type of part def-
inition is used to enable the graph printing in Tally. The part should contain at least two fields
to get 'X' and 'Y' axis. In one field the attribute Graph Label is used and in the second field the
attribute Graph Value is used.

The attribute Graph Type


The attribute Graph Type of part definition enables the creation of a graph. The graph then can
be displayed on screen or it can be printed along with the report. The attribute value must be
set to Yes in order to display or print the graph.
Syntax
[Part: <Part Name>]
Graph Type : <Logical formula>
Where,
<Part Name> is the name of the part which contains the graph
<Logical Formula> can be any expression which returns the logical value Yes/No

The attribute Graph Label


The field attribute Graph Label is used to display the values on the X-axis of the Graph.
Syntax
Graph Label : [Yes / No]
Where,
<Logical Formula> can be any expression which returns the logical value Yes/No.

The attribute Graph Value


The field attribute Graph Value is used to display the field value as a Bar on the Y-axis of the
Graph.
Syntax
Graph Value : <Logical Formula>
Where,
<Logical Formula> can be any expression which returns the logical value Yes/No.

There can be just one field with Graph Label attribute, which displays the values on the X-
axis. But there can be number of fields with Graph Value which will display the Y-axis. Tally
automatically uses multiple colors to differentiate the various bars belonging to a set of values.

603
Advanced Reporting and Printing

Example:
Consider the following code snippet to display the graph of all Sundry Debtor ledgers and
show their corresponding Sales and Receipts for the period.
[Part : led Graph]
Line : LedGraph
Repeat : LedGraph : SD Ledgers
GraphType : Yes
Height : 100% Screen
Width : 100% Screen
Scroll : Vertical
The part “Led Graph” is enabled for displaying a graph by setting the value of the attribute
Graph Type as Yes.

[Line : LedGraph]
Fields: Led NameFld, LEd DrTurnOver, LEd CrTurnOver

[Field : Led NameFld]


Use : Name Field
Set as : $Name
GraphLabel: Yes

The value of the field “Led NameFld” is used for labelling the X- Axis.

[Field : Led DrTurnOver]


Use : Amount Field
Format :"DrCr"
Set as : $DebitTotals
GraphValue : Yes

[Field : Led CrTurnOver]


Use : Amount Field
Format : "DrCr"

604
Advanced Reporting and Printing

Set as : $CreditTotals
GraphValue: Yes
The value of the fields “Led DrTurnOver” and “Led CrTurnOver” is used for generating the
Bars and labelling the Y- Axis.

[Collection : SD Ledgers]
Type : LEdger
Childof : $$GroupSundryDebtors
BelongsTo : Yes

Figure 12.12 Graph Report

The above figure shows the Sales and Receipts of the ledgers under group Sundry Debtors.
12.2.8 Additional Attributes and Functions
Earlier in the chapter, we have discussed the mandatory attributes required for usage in
printing for various techniques. In this section we will discuss a few more attributes and
functions which are used on a case to case basis as per requirement.

605
Advanced Reporting and Printing

Generic Attributes
Report Attribute-Print Set
The attribute Print Set is used at Report definition. It is used to set the value to the variable for
the report, only in print action/mode. This is a dual list attribute.
Syntax
Print Set : <Variable Name> : <Value>
Where,
<Variable Name> is the name of the variable
<Value> is the value to be set to the variable

Form Attribute-Print After Save


The attribute Print After Save is a Form definition attribute which determines whether the
form has to be printed immediately after saving. If the attribute is set to Yes, then after saving
the form Tally will prompt you whether you wish to print the same.
Syntax
Print After Save : <Logical Formula>
Where,
<Logical Formula> can be any expression which returns the logical value.

Example:
[!Form: POS Invoice Color]
Background : @@SV_POS
Print : POS Invoice Print
Print After Save: “Yes”
Line Attribute – Next Page
The definition Line supports Next Page attribute to specify the condition for the current line to
be printed on the subsequent page. It accepts a logical formula as its parameter.
Syntax
[Line: <Line Name>]
Next Page : <Logical Formula>
Where,
<Logical Formula> can be any expression which returns the logical value.

606
Advanced Reporting and Printing

Example:
[Line: DSP Vch Explosion]
NextPage : NOT $$DoExplosionsFit
In the above example if the exploded part does not fit the current page then the entire line is
moved to the next page.

Form/Part/Line/Field Attribute – DMP Mode


This attribute is used to specify the style in case of Dot Matrix Mode of printing.
Syntax
[Line: <Line Name>]
DMP MODE: <DMP Mode string>
Where,
<DMP Mode String> DMP Mode can take following values. 'Normal', 'Bold ', 'Italics',
'Underline', 'Condensed', 'Enlarged', 'Double Line'.

Example:
[!Form: Columnar Ledger]
DMPMode : Condensed

Form/Part/Field Attribute - Print BG


This attribute allows the background color to be defined for the Form, Part and Field in print
mode. The color name specified here has to be a valid TDL definition. The color thus applied
to the Form/Part/Field definition will not be displayed on the screen but it will be printed in
specified color on the color printer and in shades of grey on the black & white printer.

Syntax
PrintBG: <Color Name>
Where,
<Color Name> is the name of the color defined either in Default TDL or User TDL.

Example:
[Part: Party Details]
Background: Red
Print BG : Green

607
Advanced Reporting and Printing

In the above code the, the part “Party Details” has Red color as background in display mode
whereas Green in Print mode.

Border/Field Attribute – Print FG


The Print FG attribute can be used in definitions Field and Border. It is used to set the fore-
ground color for the Field in print mode. At the border definition this attribute is used give the
color to the border in print mode.
Syntax
[Field : <Field Name>]
Print FG : <Color Name>
Where,
<Color Name> is the name of the color defined either in Default TDL or User TDL.

Example:
[Field: Party Ledger Name]
Print BG : Red
Color : Green
Print FG : White

Printing Related Functions


In this section we will discuss the various functions used in context of Printing.

$$InPrintMode
The function ‘InPrintMode’ checks whether the report is in the print mode or not. It returns
True if the report is in the print mode else it returns False.

Syntax
$$InPrintMode

Example:
[Line: Employee SalaryBorder]
Field : Simple Field
Invisible: NOT $$InPrintMode
Border : Thin Bottom: $$InPrintMode

608
Advanced Reporting and Printing

The line Employee Salary border is displayed in print mode with a thin border at the bottom.

$$InDMPMode
The function ‘InDMPMode’ checks if the format for printing the report is Dot Matrix mode. It
returns True if the print format selected for printing is Dot Matrix mode else it returns False.
Syntax
$$InDMPMode
Example:
[Field: BSAmt]
Option : Small Size Field : $$InDMPMode

The optional field ’Small Size Field’ is implemented only in the Dot Matrix mode.

$$InDraftMode
The function ‘InDraftMode’ checks if the format for printing the report is Quick/Draft mode.
It returns True if the print format selected for printing is Quick/draft mode else it returns False.
Syntax
$$InDraftMode
Example:
[Field: PJR To]
Set as : If $$IsDr:$Amount then "" else $$LocaleString:"To"
Width : If $$InDraftMode then 3 else 2
$$InPixelMode
The function ‘InPixelMode’ checks if the selected print format is Neat mode. The function
returns True if the report Neat mode is selected else it returns False.
Syntax
$$InPixelMode
Example:
[System: Formula]
NumberWidth : If NOT $$InPixelMode then 7 else 8
$$IsMultiPagePrintJob
The function ‘IsMultiPagePrintJob’ checks if the printing spans across multiple pages. It
returns TRUE if more than one page is being printed else returns FALSE.

609
Advanced Reporting and Printing

Syntax
$$IsMultiPagePrintJob
Example:
[Field: DSP PageNo]
Inactive : NOT ##PrintWithPageNo AND NOT $$IsMultiPartPrintJob
$$IsLastOfSet
This function is used to check if the current form is the last form being printed. It returns True
if the current form is the last form being printed else returns False.
Syntax
$$IsLastOfSet
Example:
[Line: DSP Vch Explosion]
Next Page : (($$LineNumber = $$LastLineNumber) AND +
$$IsLastOfSet)
$$DoExplosionsfit
In case of printing, if a line is exploded, then this function can be used to check whether the
exploded part fits within the current page. If the number of lines to be printed does not fit in
the available space for printing then the page break occurs. This function doesn’t require any
parameter and returns logical value. It returns logical value Yes if it is true.
Syntax
$$DoExplosionsFit
Example:
[Line: EXPSMP InvDetails]
NextPage : NOT $$DoExplosionsFit OR (($$LineNumber = +
$$LastLineNumber)
$$BalanceLines
This function is used to check balance number of lines in the repeated lines, including the
exploded part-lines present, in a given part. Scroll : Vertical must be specified at the Part defi-
nition in order to use this function. This function too does not require any parameter and
returns Numerical value.

Syntax
$$BalanceLines
Example:
[Line: LR Detail]

610
Advanced Reporting and Printing

NextPage : (($$LineNumber = $$LastLineNumber) AND +


($$BalanceLines < 3))
In the above example, if the Balance number of lines is between 0 and 3, it will print the
remaining lines in next page.

$$IsFirstChildInNextPage
The function is used to check whether the child object is printed on the next page and its parent
object on the current page. This function can be used in the attribute ‘Next Page’ of Line defi-
nition to print the parent in the same page as of its first child.
Syntax
$$IsFirstChildInNextPage
Example:
[Line : MyTBDetails]
NextPage: $$IsFirstChildInNextPage

Printer Related functions


$$PrintersExist
The function returns TRUE if printer is installed on the System and returns FALSE if no
printer is installed.
Syntax
$$PrintersExist
$$Port Name
This function returns the Port name of the selected printer if Printer Name is supplied as a
parameter. In absence of any parameters, it returns the Port Name of the first printer in the list
of installed printers.
Syntax
$$PortName:<Printer Name>
Where,
<Printer Name> is the name of the printer available.
Example:
[Field: DSP PrinterName]
Set : ##SVPrinterName + " (" + $$PortName:##SVPrinterName + ")"

611
Project Work
Project Work: Inventory Management –
Garment Store

A Garment Store Glitz Apparels, who are using Tally.ERP9 require some modifications to suit
their business specific needs.The requirement is more focussed towards Inventory Manage-
ment. Details like Brand, Colour, Size, etc. need to be captured along with their Stock Items
and the same needs to be used during Voucher Entry, Label Printing and Invoice Printing.
While Purchasing the Items, labels for the Stock Items are being printed as many as number of
Items purchased. While selling the Items, the corresponding Brand, Product Type, Colour and
Size Information are being displayed.Sales Invoice For Cash and Credit Sales are required to be
customized as per their specific formats. Stock Summary Reports must be modified to contain
Columns for Brand, Colour, Size, etc. and Matrix Report on Itemwise Brandwise Sizes are
needed to have an analysis.
1. F11 Features

615
Project Work

1.1 Implementation Logic


F11 (Company Features) -> F2 (Inventory Features)
1. Add an option "Enable Garment Module ?"
2. If the Enable Garment Module is enabled, query if Item Code needs to be generated
automatically.
3. Invoke a Sub-Form if the above query is enabled.
4. Design a Report querying for the supporting informations like Starting Number,
Width of Numerical Part, etc.
5. Repeated values of Prefix, Starting Number and Suffix details to be stored using
Aggregate UDF

616
Project Work

2. Stock Item Master Creation

2.1 Implementation Logic


Inventory Info Masters
1. Add Menu Items for Masters Type of Product, Brand Name, Color and Fit Type
2. Within Sub-Menu of Every Master, create a separate Menu to Create, Display, Alter
as in Stock Group, Stock Item Master, etc.

617
Project Work

2.2 Implementation Logic


Inventory Info Masters – Type of Product Master
1. New Report for Type of Product Master must be written associating a default Object
Stock Category with a hidden flag representing the master typeviz., Type of Product,
Brand, Color or Fit Type.
2. When user enters the report in Display or Alter, the List of Masters should only be the
relevant ones and not all the Stock Categories should be visible. For example, if the
user has entered into Brand Menu, the Sub Menu Alter should display a list of Brands
only

618
Project Work

2.3 Implementation Logic


Inventory Info Masters – Type of Product Master
1. Same Report designed for Type of Product Master can be used with a relevant hidden
flag set representing the Brand and different Report Title set.

619
Project Work

2.4 Implementation Logic


Inventory Info Masters – Fit Type Master
1. Using Brand Report, one needs to locally modify the report to remove unwanted stor-
ages and accept only relevant input storages.

2.5 Implementation Logic


Inventory Info Masters – Stock Item Master
1. Add a line at beginning Is the Item of Garment Type?

620
Project Work

2. On enabling the above, a Sub Form must pop up requesting for relevant Brand, Prod-
uct and other details wherein the table from relevant master list must be displayed in
the respective fields and the entered values must be stored in UDF.
3. The Field Stock Item Name must be automatically set with the concatenated values
from Brand, Type, Colour & Size and the user should not be allowed to alter this
Field.
4. First Alias Field must be set with the auto generated code if the same is enabled in
F11 Features else user needs to enter values.
Code generation logic:
a. Gather a Collection of Items by grouping over the number portion of code and
sorting the objects in descending order.
b. Extract the Code from the first Object within the Collection, add one to it and con-
catenate the number with the Prefix, Suffix and the selected master codes.
5. Allow the user to enable Price List within the current Stock Item and on enabling, a
Sub Form must popup like the one displayed above
Hint:Grouping over Objects can be done using User Defined Functions and Action For Token
within.
3. Voucher Type Master Alteration
3.1 Purchase Voucher Type Creation

621
Project Work

3.2 Sales Voucher Type Creation

3.3 Implementation Logic


Inventory Info Masters - Voucher Type Master
1. Add a line Use for Garment Purchase or Use for Garment Sales? based on the Type of
Voucher selected Purchase or Sales respectively.

622
Project Work

4. Voucher Entry
4.1 Garment Purchase Voucher

On saving the above Purchase Voucher, the following Label should be printed, 2 labels in a
row and as much labels as specified for each item within the current voucher, i.e., for 50 Pcs of
an Item, it should print 25 Rows and 2 Columns labels for this Item

623
Project Work

4.2 Implementation Logic


Inventory Info Masters - Garment Purchase
1. Provide a new Field within Inventory Entries to enter value to Print/Reprint Labels.
By default, the Billed Qty value should be pre-filled and user can change it if
required.
2. As soon as Item Name is entered, a sub form should popup repeating for all the Sizes
as configured in the Size Master for the Selected Item
3. On entering the Item Sizes and respective Quantities, the Sum of Quantity should be
updated in the Billed Quantity as well as Print Labels Field
4. On saving the Purchase Invoice, using event On Form Accept, we need to call an user
defined function to print Labels for each Item as per the numbers entered.
a. We need to walk over the Inventory Entries and push the Items in the List Varia-
ble.
b. Finally design a Report to print each label in the above format.
5. Within the Report, have 2 Horizontal Parts wherein the same lines get printed in both
parts and Repeat should repeat the total number of values divided by 2.

All the above should work only if the value for Use for Garment Purchase is
enabled in the Voucher Type Master

624
Project Work

4.3 Garment Sales Voucher

4.4 Implementation Logic


Inventory Info Masters - Garment Sales
1. As soon as Item Name is entered, a sub form should popup repeating for all the Sizes
as configured in the Size Master for the Selected Item
2. On entering the Item Sizes and respective Quantities, the Sum of Quantity should be
updated in the Actual as well as Billed Quantity Field
3. Explode the Item Line for displaying details of Brand, Product Type, Colour and Size

All the above should work only if the value for Use for Garment Sales is
enabled in the Voucher Type Master

625
Project Work

5. Invoice

626
Project Work

5.1 Implementation Logic


Invoice Printing - Sales
1. Design an Invoice based on the Party Ledger selected, if Cash, the first format i.e.,
Cash Memo, if Party then second format i.e., Customer Invoice needs to be printed.
6. Garment Store Reports
6.1 Stock Summary with Brand/Type/Colour/Size (Existing Report - Stock
Summary)

6.2 Instructions for Filtering


1. On filtering based on Brand, Product Type, Colour or Size, a Report to be displayed
with relevant values listed in the Table. For ex., if Brand is selected, list of Brands
must be populated within the Table shown in the subsequent report.
2. All the Tables must contain an Item All Items which removes the Filter.
6.3 Implementation Logic
Reports - Stock Summary
1. In the Stock Summary Report, insert fields for Brand, Colour, Size, etc. and set these
respective values referring to the corresponding Stock Item Master

627
Project Work

2. On filtering based on Brand, Product Type, Colour or Size, a Report to be displayed


with relevant values listed in the Table. For ex., if Brand is selected, list of Brands
must be populated within the Table shown in the subsequent report.

6.4 Instructions for Filtering


1. On filtering based on Brand, Product Type, Colour or Size, a Report to be displayed
with relevant values listed in the Table. For ex., if Brand is selected, list of Brands
must be populated within the Table shown in the subsequent report.
2. All the Tables must contain an Item All Items which removes the Filter.

6.5 Implementation Logic


Reports - Stock Summary
1. In the Stock Summary Report, insert fields for Brand, Colour, Size, etc. and set these
respective values referring to the corresponding Stock Item Master
2. The values of Purchase, Purchase Returns, Sales, Sales Returns can be retrieved by
grouping over the Stock Items within their respective Voucher Types and aggregating
the Quantities.

628
Project Work

7. Columnar Reports
7.1 Brandwise Itemwise Sizewise Sales (New Report)

7.2 Implementation Logic


Reports - Brandwise Itemwise Sizewise Sales
1. Gather a Collection of Sales Vouchers, group them by Items, Brand and Sizes
2. Subsequently, using the variable and DSP Repeat Collection, render the Columns i.e.,
Sizes
3. Finally using Search Key and Function CollectionFieldByKey, place the values
against appropriate Row Column Intersection Fields

629
Project Work

8. Color Scheme

630
Use Cases
Use Cases

1. Use Case I – Import from Excel/Text


1.1 Scenario
Company ABC Company Limited. which is dealing in trading business has started using
Tally.ERP 9 from the current financial year. This Company deals in purchase and sales of
Hardware Peripherals like Computers, Printers, Pen Drives, etc. Since, there are many Stock
Items that is required to be created in the Company in Tally; they wanted this bulk master
creation to be automated. Their current system allows these master data to be exported either to
Excel File or a Comma Separated Text File. Hence, the Management has approached us to
provide a tool to automate this process i.e., importing the stock items from Excel or text file to
Tally.

1.2 Functional Demo


Firstly, a configuration report is provided to accept the variable details of the file including the
header availability and the column mapping. Post Import, an error report and/or log file can be
displayed as selected by the user.

633
Use Cases

Following is the screen capture of the Configuration with default Excel Format:

Figure 1 Import configuration screen

Since, Excel is widely used for representing columnar info, Excel format is selected by
default. But the user has the liberty to select any source Text or Excel and specify the appropri-
ate file info. If the user happens to select the Text Format, an additional parameter i.e., the
separator character which separates the columns, has to be specified apart from the other
details.

634
Use Cases

Following is the screen capture of the Configuration with Text Format selected:

Figure 2 Import configuration screen -Text

Once the details are entered, a confirmation message is prompted to begin or cancel the import
process. If the user has enabled the option to display the error report, after the import process,
a report is shown with the stock items imported and the status i.e., imported successfully,
Item 1 already exists, Group Computer Peripherals does not exist, etc.

635
Use Cases

Following is the screen capture for the Import Status Report:

Figure 3 Import Status report

On viewing the List of Stock Items, the Items which display status in the above report as
Imported Successfully will also be available.

636
Use Cases

Following is the screen capture of the Stock Items post Import process:

Figure 4 Items after Import

1.3 Solution Development


The import from an excel file or a text file is simplified as the user can specify the import
details. The File I/O capabilities are used to achieve this.
Following are the steps followed to import the contents from Excel or Text File:
1. A user configurable report is provided to display the Source data information. The
value entered by the user is captured in System Variable.

Local: Field: Name Field : Modifies: UsCs SIC Source: Yes


Local: Field: Name Field : Variable: UsCs SIC Source
|
Local: Field: Name Field : Modifies: UsCs SIC DirPath: Yes
Local: Field: Name Field : Variable: UsCs SIC DirPath

637
Use Cases

[System: Variable]
UsCs SIC Source : "Excel"
UsCs SIC DirPath : "C:\Tally.ERP9"

2. On saving the configuration report i.e., on accepting the form, the function to import
the stock item is called.

On: Form Accept : Yes : FORM ACCEPT


On: Form Accept : Yes : Call: UsCs Import Stock Items

3. A Function UsCs Import Stock Items is defined.


a. Firstly the format of the source file is being checked and subsequently, based on
the format specified by the user, Excel or Text File is being opened using Action
OPEN FILE in read mode.

20 : IF: ##UsCsSICSource = "Excel"


30 : OPEN FILE: @@UsCsTotFilePath: Excel: READ
40 : ELSE:
50 : OPEN FILE: @@UsCsTotFilePath: Text: READ
60 : ENDIF
b. If the source is Excel, the data from the individual cells are read and added as an
element in the list variable.

120 : WHILE: NOT +


$$IsEmpty:($$FileReadCell:##Row:##ItemColumns.ItemName)
130 : LIST ADD EX : Item Details
140 : SET : ItemDetails[$$LoopIndex].ItemName: +
$$FileReadCell:##Row:##ItemColumns.ItemName
150 : SET : ItemDetails[$$LoopIndex].ItemGrp: +
$$FileReadCell:##Row:##ItemColumns.ItemGrp
160 : SET : ItemDetails[$$LoopIndex].ItemUOM: +
$$FileReadCell:##Row:##ItemColumns.ItemUOM
170 : INCREMENT: Row

638
Use Cases

180 : END WHILE

c. If the source is Text, the text file is read line by line and added as an element to the
list variable.

200 : SET : Counter: 1


210 : WHILE: NOT $$FileIsEOF
220 : SET : Temp Var : $$FileRead
230 : IF : NOT $$IsEmpty:##TempVar AND +
(NOT ##UsCsSICIncHeader OR (##UsCsSICIncHeader +
AND $$LoopIndex > 1))
240 : LIST ADD EX: Item Details
250 : SET : ItemDetails[##Counter].ItemName: +
$$UsCsSICExtractDet:##TempVar:##ItemColumns[].ItemName
260 : SET : ItemDetails[##Counter].ItemGrp: +
$$UsCsSICExtractDet:##TempVar:##ItemColumns[].ItemGrp
270 : SET : ItemDetails[##Counter].ItemUOM: +
$$UsCsSICExtractDet:##TempVar:##ItemColumns[].ItemUOM
280 : INCREMENT: Counter
290 : ENDIF
300 :END WHILE

4. A collection is populated using the List variable as data source.


[Collection: UsCsImp StockItem]
Data Source : Variable : Item Details

[Collection : UsCs Imp StockItem Summ]


Source Collection : UsCsImp StockItem
By : SICStockItem : $ItemName
By : SICStockGroup: $ItemGrp
By : SICStockUOM : $ItemUOM
Filter : UsCs NonEmpty Item

639
Use Cases

5. Now the Stock Item objects are created. If the item cannot be imported then the item
details are written in the error file or compound variable based on the option selected
for displaying i.e., Report or Log.

380 : WALK COLLECTION: UsCs Imp StockItem Summ


390 : SET : Last Status: ""
400 : IF: $$IsEmpty:$Name:StockItem:$SICStockItem
410 : NEW OBJECT : Stock Item
420 : SET VALUE : Name : $SICStockItem
430 : IF : NOT $$IsEkmpty:$Name:StockGroup:$SICStockGroup
440 : SET VALUE: Parent : $SICStockGroup
450 : ELSE:
460 : SET : LastStatus : "Group " + $SICStockGroup +
"does not exist"
470 : ENDIF
480 : IF : NOT $$IsEmpty:$Symbol:Unit:$SICStockUOM
490 : SET VALUE: Base Units: $SICStockUOM
500 : ELSE:
510 : SET : LastStatus : "Unit " + $SICStockUOM +
"does not exist"
520 : ENDIF
530 : IF : $$IsEmpty:##LastStatus
540 : SAVE TARGET
550 : SET : Last Status: "Imported Successfully"
560 : ENDIF
570 : ENDIF
;; Writing Import Status to the LOG File if LOG File is to be displayed at the end
580 : IF : ##UsCsSICOpenLogFile
590 : WRITE FILE LINE: $SICStockItem + ##UsCsSICTextSep +
##LastStatus
600 : ENDIF

640
Use Cases

;; Updating List of Compound Variables is Status is to be displayed in a Report

610 : IF : ##UsCsSICDisplayReport
620 : LIST ADD EX : ItemImportStatus
630 : SET : ItemImportStatus[##Counter].ItemName:+
$SICStockItem
640 : SET : ItemImportStatus[##Counter].Status: ##LastStatus
650 : INCREMENT : Counter
660 : ENDIF
670 : END WALK
6. If the format selected is Report, then the stock item name and the status are updated
in a compound variable. If the format selected is Log file, then the Action WRITE
FILE LINE is used to write to a text file.

590 : WRITE FILE LINE: $SICStockItem + ##UsCsSICTextSep +


##LastStatus
Post import process, if the user had chosen to display the error report, the Action DISPLAY is
used to display the report showing list of Items created and ones not created along with
reasons for the same.

690 : IF : ##UsCsSICDisplayReport
700 : DISPLAY : UsCs SIC Error Report
710 : ENDIF

7. Post import process, if the user had chosen to display the log file then the log file
opens up.
720 : IF : ##UsCsSICOpenLogFile
730 : EXEC COMMAND: @@UsCsErrorFilePath
740 : ENDIF
8. In the error report, line is being repeated over the collection populated using the list
variable as the data source.

641
Use Cases

2. Use Case II – Multiple Saved Configurations for Report


2.1 Scenario
A Company, ABC Company Ltd., which is in trading business, is using Tally.ERP 9. It deals
with purchase and sale of computers, printers, etc. Frequently, the director of the company
views various financial reports. But, each time these reports are opened, it needs to be config-
ured as required with opening, inwards, closing, etc. They have identified a need to have an
option to retain and restore different set of configurations for every report. In other words,
they needed a mechanism to have multiple configurations for the same report and apply the
required configuration as and when needed.
2.2 Functional Demo
The solution is developed using the language capability Save Variable and Load variable.
Prior to getting into the technical aspects, let us first take a look at the same functionally.
Tally.ERP 9 has been extended to save and restore various configurations for reports. For
thism two buttons Save Config and Retrieve Config are added in the reports.
The selected configuration is saved as a file in the local Tally.ERP9 folder. The file name is
appended with the Report Name so as to display a report specific configuration, i.e., user can
view only list of Stock Summary Configurations in Stock Summary and Trial Balance Config-
urations in Trial Balance.

642
Use Cases

Saving Multiple Configurations


Let us take an example of Stock Summary report. When user sets some configuration, the
below screen appears:

Figure 5 Setting required configurations

On accepting the configuration screen, the configuration gets applied to the report. By
clicking on Save Config Button, one can specify the Configuration Name and accept the same
as shown below:

Figure 6 Saving the configuration with a specified name

Once the user accepts this screen, the configuration details will be saved in the file Stock
Summary_Base.pvf as the current report is Stock Summary. Hence, a Report specific con-
figuration can be maintained and retrieved. Similarly, we save another configuration with
name Stock Summary_Detailed.PVF

643
Use Cases

Retrieving Configuration to view the Report in Different Dimensions


On clicking Load Config Button, the already list of saved configuration files appear.

Figure 7 Retrieving & Selecting the Required Configuration

644
Use Cases

On selecting the required configuration, the desired configuration is set automatically as


shown below:

Figure 8 Report configured as per the selection

645
Use Cases

Again, to view the same report with another configuration, click on Load Config which
displays the list of configurations.

Figure 9 Retrieving & Selecting another configuration

646
Use Cases

On selecting the required configuration, the base report will be configured with a selection as
shown below:

Figure 10 Report configured as per the selection

2.3 Solution Development


The TDL language capability Load Variable and Save Variable is used to develop the solution
for saving multiple report configurations. Different configurations for the same report can be
saved and retrieved as per the user requirement.
The steps followed to achieve the requirement are:
1. The buttons are added to the various reports as shown below:

[Report: UsCs Stock Summary]


Use : Stock Summary
Variable : PVFFileName : String
Local: Form: Default : Add : Buttons : Blank Button6, +

647
Use Cases

UsCs Save Config, UsCs Retrieve Config

[Report: UsCs Trial Balance]


Use : Trial Balance
Variable : PVFFileName : String
Local : Form: Default : Add : Buttons :+
UsCs Save Config, UsCs Retrieve Config

2. Button Definition to Save and Retrieve Configurations


[Button: UsCs Save Config]
Key : Alt + S
Action : ALTER : UsCs ConfigName
Title : "Save Config"

[Button: UsCs Retrieve Config]


Key : Alt + R
Action : ALTER : UsCs Retrieve Config
Title : "Retrieve Config"
Inactive: $$IsEmptyCollection:UsCsListofPVFFiles
The report UsCs ConfigName is created to accept the configuration name from the user.
[Form: UsCs ConfigName]
Parts : UsCs ConfigName
On :Form Accept:Yes:SAVE VARIABLE:#UsCsReportName + "_" +
#UsCsConfigName : *.*
When the report is accepted, the action SAVE VARIABLE is launched which saves all the
variables at current scope i.e., Report within the file specified. The file name is prefixed with
the report name. e.g., Stock Summary_Base.pvf in order to have a Report specific configura-
tion.
3. A report UsCs RetrieveConfig is created to Load the selected configuration from
the list of saved configuration. The part is repeated over a collection of saved config-
uration.
[Part: UsCs RetrieveConfig]

648
Use Cases

Lines: UsCs RetrieveConfig1, UsCs RetrieveConfig2, +


UsCs RetrieveConfigs
Repeat: UsCs RetrieveConfigs : UsCs ListofPVFFiles
The selected configuration value is then passed as parameter to the function SplitFileName so
as to remove the prefixed Report name such that user can view only the configuration name
specified.
[Field: UsCs RetrieveConfigs]
Use : Name Field
Set As : $$SplitFileName:$Name
Style : Normal
Delete : Key
Add: Key : UsCs SetVar and Form Accept

The Keys declared at the Field are defined as follows:


[Key: UsCs SetVar and Form Accept]
Key : Enter
ActionList: UsCs SetVar, UsCs Form Accept
Mode : Edit

[Key: UsCs SetVar]


Key : Enter
Action: Set : PVFFileName: $$Value
;; This sets the field value to the variable so that parent report can restore from the PVF file

[Key: UsCs Form Accept]


Key : Enter
Action: Form Accept
The collection UsCs ListofPVFFiles uses the Data Source attribute to select the files from the
specified directory.
[Collection: UsCs ListofPVFFiles]
Data Source: Directory: "."
Filter : UsCs OnlyPVFFiles

649
Use Cases

The collection is filtered to contain the report specific PVF files as follows:
[System: Formula]
UsCs OnlyPVFFiles: $Name CONTAINS "PVF" and ($Name CONTAINS +
$$ContextKeyword:Yes OR $Name CONTAINS +
$$ContextKeyword)
When the report is accepted, the action LOAD VARIABLE is then launched with the saved
variable values from the selected file loaded and the respective configuration settings are
applied to the current report.
3. Use Case III – Multiple Email Configurations
3.1 Scenario
ABC Company Ltd., a manufacturing company is having Head Office in Bangalore and
branch offices at Delhi, Mumbai, Kolkata and Chennai. The company is using Tally.ERP 9 in
all their locations.
The Head Office and Branch Offices are using the e-mail capability of Tally extensively to
send the reminder letters/outstanding statements to the customers.
The System Administrator at the Head office will be facilitating the Branch office staff for
email configurations in Tally. The company is using its own mail server and also using
another mail server “SIFY”. If there is a change in the mail server, the system admin needs to
communicate this information to the branch staff and they will be updating the email configu-
rations accordingly in Tally.ERP 9.
Now the company wants to set the email configurations centrally for all the branches so that
branch staff need not struggle for email configurations particularly when there is change in
mail server. This solution provides the facility of saving multiple configurations in different
files and later loading it from the file based on user selection.
3.2 Functional Demo
At present in Tally.ERP 9, the users need to set the email configurations locally and update
required details.
Configurations can be created centrally and shared among the locations. So that the users
need not set the email configuration every time. They have to simply load the configuration
from the file. This can be achieved using the actions SAVE VARIABLE & LOAD
VARIABLE.
Before looking into the design logic, we will have a functional demo.
Let us suppose ABC Company Ltd is using its own mail server and another mail server Sify in
Head Office and its branch offices.

650
Use Cases

Saving Email Configurations


Let us suppose the System Administrator in Head Office wants to save the required email con-
figurations in Tally.ERP 9 for HO and Branches
Gateway of Tally > F12 (Configure) > E-Mailing > Email configuration screen will appear
as shown below:

Figure 11 Email configuration screen

The System Admin needs to save the Configurations for the mail servers Rediff Mail and Sify.
Hence, he has to specify the Email server as “User Defined” and enter the required configura-
tion settings as shown in the below screen capture.

Figure 12 User defined Email configuration

651
Use Cases

Now the System Admin has to press Alt+S or click on the Button Save Config. The below
screen will appear and he has to enter the configuration file name.

Figure 13 Save Email configuration screen

Once the System Admin accepts this screen, the configuration details will be saved in the file
rediff.pvf. Similarly he has to create the Configuration for the mail server Sify.
The files will be created in the Tally.ERP 9 application folder as shown in the below screen
shot.

Figure 14 Tally folder

The admin can share these two files to the staff in HO and Branch Offices and they should
place the file in the respective Tally.ERP 9Application folders.

Loading Configurations
Gateway of Tally > F12 (Configure) > E-Mailing > the Email configuration screen will be
displayed with the previously set configurations.

Figure 15 Load configuration screen

652
Use Cases

Now the user at the HO/Branch wants to load the configurations for the email server Rediff.
He has to press Alt+L or click on the Button Load Config and enter the file name as shown in
the below screen shot

Figure 16 Load Email file configuration screen

Accept the screen then the Email Configuration Report will display the configuration details
loaded from the file Rediff. Accept the email configuration screen and the settings will be
applicable to all the reports.
If the user wants to mail the report Balance Sheet, he will select the Balance Sheet report and
press Alt + M, the below configuration report will appear

Figure 17 Mailing Balance sheet configuration screen

We can observe here that the configuration details are prefilled as per our requirement. Simi-
larly, we can save/load multiple configurations.

653
Use Cases

3.3 Solution Development


The steps followed to achieve saving Multiple Email Configuration are:-
Declaring variables at Report Level
The variables SVMailServerName, SVMailServer, SVMailFormat, SVMailUseSsl, etc.
declared at the Report are persisted.
[#Report: EMail Configuration]
Variable: SVMailServerName, SVMailServer, SVMailFormat,+
SVMailUseSsl
Variable: SVMailUseSSLOnStdPort, SVMailAuthUserName, +
SVExportFormat
Saving Configuration
A Button is added to the Form. On clicking the same, a User Defined Function is called,
which, in turn, triggers a report which prompts a File Name from the user. All the Report
scope variables are being persisted in the specified file with the help of action SAVE
VARIABLE.

Loading Configurations
A button is added to the Form. On clicking the same; a User Defined Function is invoked
which, in turn executes a report that accepts the File name from the user. The report scope
variables are being loaded from the file with the help of action LOAD VARIABLE.
Please refer to the below code snippet for Save and Load configurations.
[Function: UsCs SaveLoadVar]
Parameter: IsSaveVar : Logical: Yes
Variable : ConfigNamewithExt: String: Yes

00 : EXECUTE : UsCs SaveLoadConfig


;; Correcting the file name entered with or without extension by user
06 : IF : ##SaveLoadConfigName CONTAINS ".Pvf"
10 : SET : ConfigNamewithExt: ##SaveLoadConfigName
20 : ELSE:
30 : SET : ConfigNamewithExt: ##SaveLoadConfigName + ".pvf"
40 : ENDIF
;; Saving or Loading the variables based on parameter value
50 : IF : NOT $$IsEmpty:##SaveLoadConfigName

654
Use Cases

60 : IF: ##IsSaveVar
70 : SAVE VARIABLE: ##ConfigNamewithExt
80 : ELSE:
90 : LOAD VARIABLE: ##ConfigNamewithExt
100 : ENDIF
110 : ENDIF
The corresponding field values need to reflect the values of the variables loaded from the file.
This is handled using the following code:
Local: Field: DSPMailServer: Set as: If #DSPMailServerName +
Contains $$SysName:UserDefined Then ##SVMailServer Else +
If #DSPMailServerName NOT Contains $$SysName:UserDefined +
Then $$GetMailServerAddr:#DSPMailServerName Else+
##SVMailServer
Local: Field: DSPMailServerName: Set As: ##SVMailServerName
Local: Field: DSPMailFormat: Set As: ##SVMailFormat
Local: Field: DSPMailUseSsl: Set As: ##SVMailUseSsl
Local: Field: DSPMailUseSSLOnStdPort : Set As : +
##SVMailUseSSLOnStdPort
Local: Field: DSPMailAuthUserName: Set As: ##SVMailAuthUserName
Local: Field: DSPFinalExportFormat: Set As: ##SVExportFormat
Also. if the field values are changed, the Report level variables need to be modified with those
values. This is handled using the following code:
Local: Field: DSP MailServerName: Modifies: SVMailServerName :
Yes
Local: Field : DSP MailServer: Modifies: SVMailServer : Yes
Local: Field : DSP MailFormat: Modifies: SVMailFormat : Yes
Local: Field : DSP MailUseSsl: Modifies: SVMailUseSsl : Yes
Local: Field : DSP MailUseSSLOnStdPort : Modifies: +
SVMailUseSSLOnStdPort: Yes
Local: Field : DSP MailAuthUserName : Modifies: +
SVMailAuthUserName: Yes
Local: Field : DSP FinalExportFormat: Modifies: +

655
Use Cases

SVExportFormat: Yes
On accepting the Form EMail Configuration, a User Defined Function is called to set the
System Variable values with the Report values such that, the altered configuration gets
effected in all the reports.
Please refer the below Code Snippet:
[Function: UsCs Update System Variables]
10 : SET : ().SVMailServerName: ##SVMailServerName
20 : SET : ().SVMailServer: ##SVMailServer
30 : SET : ().SVMailFormat: ##SVMailFormat
40 : SET : ().SVMailUseSsl: ##SVMailUseSsl
50 : SET : ().SVMailUseSSLOnStdPort: ##SVMailUseSSLOnStdPort
60 : SET : ().SVMailAuthUserName: ##SVMailAuthUserName
70 : SET : ().SVExportFormat: ##SVExportFormat

4. Use Case IV – Duplicating Vouchers


4.1 Scenario
A Company, ABC Company Limited, which is in trading business, is using Tally.ERP 9. The
Company deals in purchase and sale of hardware peripherals such as computers, printers, etc.
They had a peculiar requirement wherein Payment and Receipt entries were repeated often.
Hence, they required an option to duplicate these vouchers and they would further alter the
required values like Date, Narration, etc. manually which would save lot of their time.

656
Use Cases

4.2 Functional Demo


The vouchers in the company can be viewed by Display >Day Book as follows:

Figure 18 Daybook

657
Use Cases

A function is called from menu which duplicates all the Payment and Receipt vouchers of
Company and then shows the list of vouchers Duplicated during the current process.

Figure 19 Daybook with duplicated vouchers

4.3 Solution Development


The steps followed to achieve the requirement are:
1. A summary collection is created out of the source objects viz., Payment and Receipt
Vouchers as shown below:
[Collection: UsCs Dup PymtRcpt]
Source Collection: UsCs Dup PymtRcpt Vouchers
Fetch : Date, VoucherTypeName, Narration,+
LedgerEntries.*

[Collection: UsCs Dup PymtRcpt Vouchers]


Collection: UsCs Dup Pymt Vouchers, UsCs Dup Rcpt Vouchers

658
Use Cases

[Collection: UsCs Dup Pymt Vouchers]


Type : Vouchers: Voucher Type
Child Of : $$VchTypePayment

[Collection: UsCs Dup Rcpt Vouchers]


Type : Vouchers: Voucher Type
Child Of : $$VchTypeReceipt
2. A function is written to walk the collection of receipt and payment vouchers created
above and duplicate them.

[Function: UsCs Voucher Duplication]


10 : WALK COLLECTION: UsCs Dup PymtRcpt
20 : SET : SVViewName : $$SysName:AcctgVchView
3. A new object is created as target object and the values of the methods are set from the
current voucher object.

30 : NEW OBJECT: Voucher


40 : SET VALUE : Date : $Date
50 : SET VALUE : VoucherTypeName : $VoucherTypeName
60 : SET VALUE : Narration : $Narration + ##VarNarration
70 : SET VALUE : PersistedView : ##SVViewName

4. The collection Ledger Entries of the current voucher is walked and a new ledger
entry object is inserted in the target object context. The values of the target Ledger
Entry object are set from the current Ledger Entry source object. After setting all the
Methods within the Sub Object ledger entries, the voucher object is once again set as
the target object with a Set Target : ...

80 : WALK COLLECTION : LedgerEntries


90 : INSERT COLLECTION OBJECT : Ledger Entries
100 : SET VALUE : Ledger Name : $LedgerName
110 : SET VALUE : IsDeemedPositive : $IsDeemedPositive
120 : SET VALUE : Amount : $Amount

659
Use Cases

130 : SET TARGET: ..


140 : END WALK

5. The Duplicated vouchers are then saved to the data and a report displays all the dupli-
cated vouchers.

150 : CREATE TARGET


160 : END WALK
170 : DISPLAY: UsCs Dup Entries in Daybook
180 : RETURN
Since the Narration within the Vouchers are updated with the Data and Time info, it becomes
easy to filter the same within the daybook to display the list of vouchers updated in the current
iteration.

5. Use Case V – Inter Company Data transfer


5.1 Scenario
A firm ABC Company Ltd. using Tally.ERP 9 has a subsidiary company Global Enterprises.
ABC Company Ltd. makes payment to Global Enterprises. Since, this is an inter branch
transfer, the payment entry from one branch has to posted as receipt entry in another branch
and vice versa.
5.2 Functional Demo
A payment entry in ABC Company Ltd. should be posted as a receipt entry in Global Enter-
prises and a receipt entry as payment.
An option Inter Company Data Transfer is added.
Perform following steps before selecting the option Inter Company Data Transfer:
1. Create two different companies called Global Enterprises and ABC Company Ltd.
2. Select the Company ABC Company Ltd. as active company. The current company
acts as a Source Company. Pass few payment vouchers in the current company. On
entering the entries, the day book looks as shown below:

660
Use Cases

Figure 20 ABC Company Day book

3. After clicking the option Inter Company Data Transfer, the second company open is
considered as Target Company.
4. The following confirmation screen appears:

Figure 21 Data transfer confirmation screen

5. All the payment vouchers from the company ABC Company Ltd. are transferred as
Receipt to the company Global Enterprises.

661
Use Cases

6. The Daybook for the Global Enterprises after data transfer is as shown.

Figure 22 Global Enterprises Day book

5.3 Solution Development


In order to transfer a payment entry from ABC Company Ltd. to Global Enterprises as
receipt, the following steps have to be adhered:
1. Menu for calling function

a. A new menu item is added to call a function in order to transfer all payment entries
from ABC Company Ltd. to Global Enterprises.

Add : Key Item : "Inter Company Data Transfer" : N : CALL :+


UsCs InterCompany Data Transfer

2. Function description
a. We would require switching from ABC Company Ltd. to Global Enterprises
and after transfer of vouchers we need to switch back to ABC Company Ltd.

b. By default, the current company is considered as Source Company and the second
company from the list of opened companies is considered as target company.
00 : IF: $$SelectedCmps > 1
10 : SET : SrcCompany: ##SVCurrentCompany
;; First Non Source Company from the list of open companies is set as Target Company here
20 : SET : TgtCompany:$$FilterValue:$Name:+

662
Use Cases

ListOfCompanies:First:UsCsNotIsSrcCompany
c. A confirmation box is displayed for the data transfer
60 : QUERY BOX: "From the Company, " + ##SrcCompany +
",all the Payment Entries will be created \n”+
“as Receipt and Receipt Entries as Payment in+
the Company, "+ ##TgtCompany + "\n\n Are you +
sure?" : Yes:No

d. On the response as Yes from the user, the data from Source Company i.e. current
company is transferred to the target company. The collection of vouchers is
walked and the variable SVCurrentCompany is switched to target company.
70 : IF : $$LastResult
80 : WALK COLLECTION : UsCs PymtRcpt Vouchers
90 : SET : SVCurrentCompany : ##TgtCompany
;; Setting the current Source as Target
100 : SET TARGET
e. The voucher Type is changed to Receipt if it is Payment Voucher

110 : SET VALUE : VoucherTypeName : if $$IsPayment: +


$VoucherTypeName then $$VchTypeReceipt +
else $$VchTypePayment
120 : SET VALUE : VoucherNumber

f. Appropriate values are set for the methods of Ledger Entries collection
130 : WALK COLLECTION : LedgerEntries
140 : SET TARGET : LedgerEntries[$$LoopIndex]
150 : SET VALUE : Amount : if $$IsDr:$Amount then+
$$AsCrAmt:$Amount else $$AsDrAmt:$Amount
160 : SET VALUE: IsDeemedPositive: NOT $IsDeemedPositive
170 : SET TARGET: ..
180 : END WALK
190 : SET VALUE : Narration: ##VarNarration
;; Saving the Target Company Voucher
200 : SAVE TARGET

663
Use Cases

210 : SET : SVCurrentCompany: ##SrcCompany

g. Altering the Source Company Voucher with Updated or Transferred Voucher Flag
220 : SET TARGET
230 : SET VALUE : UsCs UpdatedVch: Yes
240 : SAVE TARGET;; Saving the Source Company Voucher
250 : END WALK
260 : ENDIF

h. Now the target company is set as current company and its Day book is displayed
to show the Vouchers Transferred to the Target Company during the current ses-
sion.
270: SET : SVCurrentCompany: ##TgtCompany
;; Displaying the Vouchers Transferred to the Target Company during the current session
280: DISPLAY: UsCs ICDT Daybook
290: SET : SVCurrentCompany: ##SrcCompany
i. In case two companies are not loaded in Tally.ERP9 then an error message is dis-
played.

MSGBOX: "Error" : "Two Companies need to be open for +


Inter Company \n” + “ Data Transfer”

j. Since only payment and receipt vouchers of ABC Company Ltd. are required the
collection of vouchers is created as shown :

[Collection: UsCs PymtRcpt Vouchers]


Collection: UsCs Pymt Vouchers, UsCs Rcpt Vouchers

[Collection: UsCs Pymt Vouchers]


Type : Vouchers: Voucher Type
Child Of: $$VchTypePayment
;; Filtering for Vouchers not updated previously
Filter : UsCs NonUpdated Vch

664
Use Cases

[Collection: UsCs Rcpt Vouchers]


Type : Vouchers: Voucher Type
Child Of: $$VchTypeReceipt
Filter : UsCs NonUpdated Vch

6. Use Case VI – Multi Company Outstanding Report


6.1 Scenario
A company ABC Company Ltd. using Tally.ERP9 operates from Bangalore and contains
various regional offices at Mumbai, Delhi, Chennai and Calcutta. All the regions are using
Tally.ERP9 and on a periodic basis, they keep receiving the data from each location. There are
some customers who deal across branches like purchase the items from Chennai and remit the
payment at Bangalore. Company ABC Company Ltd. contains outstanding receivables from
such companies in disparate data received from all branches. Hence, the management is
looking for a solution where they get a consolidated outstanding report across all branches.

6.2 Functional Demo


On selecting the Outstanding Report, it displays the bills for all the loaded companies. The
report for the loaded companies ABC Company Ltd. and DEF Corporation is as follows:

665
Use Cases

Figure 23 Multi Company Outstanding report

6.3 Solution Development


The Multi company outstanding report is developed using the Loop collection concept. A
report is written to display the outstanding bill details across companies:
The steps followed are:
1. A part is repeated over a Collection of Company to display the company names:
[Part: UsCs GrpCo LEDBILL Body]
Line : UsCs GrpCo CompanyName
;; For displaying company name
Repeat: UsCs GrpCo CompanyName: UsCs Group Company
Scroll: Vertical

666
Use Cases

The collection is defined as follows:


[Collection: UsCs Group Company]
Type : Company
Fetch : Name
Filter : UsCs NOTIsGroupCompany

2. From the line, a part is exploded to display the Bill details for the Company displayed
in Line.
[Line: UsCs GrpCo CompanyName]
Left Field : UsCs GrpCo CompanyName
Space Top : 1% Screen
Space Bottom: 1% Screen
;; Exploding Bill Details always
Explode: UsCs GrpCo LEDBILL Details
3. The Bill details are displayed by repeating a line over the collection of Bill details
from all the selected companies

[Part: UsCs GrpCo LEDBILL Details]


Lines : UsCs GrpCo LEDBILL Detail, UsCs GrpCo BILL Total
Repeat: UsCs GrpCo LEDBILL Detail : +
UsCsGrpCo CompwiseLedBills
The collection is defined as follows:
[Collection: UsCs GrpCo CompwiseLedBills]
Collection: UsCs GrpCo Ledger Bills: UsCs Group Company

The collection UsCs GrpCo Ledger Bills is gathered once for each object in the collection
UsCs Group Company. The collection UsCs GrpCo Ledger Bills is defined as follows:

[Collection: UsCs GrpCo Ledger Bills]


Type : Bills
Child Of : ##LedgerName
Filter : DueBillsFilter, AgeFilter, +

667
Use Cases

BillTypeFilter, UsCs EmptyBillsFilter

Fetch : BillDate, Parent, OpeningBalance, +


ClosingBalance, BillCreditPeriod
Fetch : LedgerEntries.MasterID, LedgerEntries.+
IsVCHOfStockJrnl
Fetch : LedgerEntries.Date, LedgerEntries.+
CurLangVoucherTypeName
Fetch : LedgerEntries.VoucherNumber, LedgerEntries.+
LedgerEntries.BillAllocations.Amount
;; All methods need to be fetched at Bill Level
Fetch : LedgerEntries.UsCs GrpCo AllocBillsTotal
Fetch : LedgerEntries.HasInventory, +
LedgerEntries.InventoryEntries.BilledQty, +
LedgerEntries.InventoryEntries.StockItemName
Fetch : LedgerEntries.InventoryEntries.Rate
Compute : Name : $$Name
Compute : BillCompanyName: $$LoopCollObj:$Name

4. The Voucher details are displayed in the exploded part by repeating the line on col-
lection Ledger entries.

[Line: UsCs GrpCo LEDBILL Detail]


Left Fields: UsCs GrpCo BillCompanyName, BILLFixed,+
BILLOp, BILLCl
Repeat : BILLCl
Local : Field: BillParty: Set As: $Parent

Space Top : If $$IsSiblingExploded Then @@Explod-


edSpace Else 0
Next Page : NOT $$DoExplosionsFit OR ($$LineNum-
ber = $$LastLineNumber +

668
Use Cases

AND NOT $$IsNextSibling)


Option : ExplodeOnEnter

Explode : UsCs GrpCo BILL Vouchers: $$InPixel-


Mode AND +
($$KeyExplode OR ##ExplodeFlag)

5. The collection to fetch the Bill's Total Amount at Voucher Level is defined as fol-
lows:

[Collection: UsCs GrpCo BillAllocTotal]


Source Collection : Default
Walk : Ledger Entries, Bill Allocations
By : LedBillName: $Name
Aggr Compute : BillAmount: SUM: $Amount
Search Key : $LedBillName

7. Use Case VII – Voucher and Invoice Customization


7.1 Scenario
A Firm ABC Company Ltd. dealing in sunmica, glass and plywood sheets is using
Tally.ERP9 for their business. They were very satisfied with the reports from Tally except for
few changes required in sales voucher including invoice printing. While doing a system study,
following requirements pertaining to sales were identified:
 An option to specify the Height and Width for the specified Item
 An additional column for accepting MRP against each item.
 Only Items with sufficient closing quantity should be allowed to be sold.The Invoice
Printing should be redesigned to print in their company specific format.
7.2 Functional Demo
The solution is implemented by using various TDL language capabilities. Before looking in to
the design logic, let us take a look at the functional demo.
When the user selects the item, to enter the Length and Breadth along with the calculated area,
a sub form is displayed as follows:

669
Use Cases

Figure 24 Area calculation

The calculated area is automatically set in the quantity field as shown below:

Figure 25 Setting Quantity based on calculated area

Subsequently, while moving from quantity field, it is checked if the quantity being sold is
available in stock. On availability, the cursor moves to the Rate else an error for Negative
Stock is displayed as shown below:

Figure 26 Negative Stock control

670
Use Cases

The cursor continues to be in quantity field. User has to enter the available quantity to move
ahead or Purchases if not entered, need to be entered first prior to this Sales entry.
On saving and printing the Invoice, default Invoice is overridden with the following format:

Figure 27 Invoice Format

7.3 Solution Development


Various TDL capabilities like User Defined Fields, report attribute Print and field attribute Sub
form are used to develop the solution. The following have been done:
Section 1: Voucher Customistion
1. To add an additional MRP column, various lines in the voucher are modified so that
the column appears appropriately irrespective of the changes in the F12 : Features :
The lines that are modified are as follows:

[#Line: EI ColumnOne]
Option : UsCs MRP ColumnOne : @@IsSales ;;Title Line1

[!Line: UsCs MRP ColumnOne]

671
Use Cases

Add: Right Fields : At Beginning : UsCs MRP


[#Line: EI ColumnTwo] ;;Title Line2

Option : UsCs MRP ColumnTwo : @@IsSales

[!Line: UsCs MRP ColumnTwo]


Add : Right Fields : At Beginning: UsCs MRP

[#Line: EI InvInfo] ;;Invoice Inventory Entries without class


Option : UsCs MRP Line : @@IsSales

[#Line: CI InvInfo] ;;Invoice Inventory Entries with class


Option : UsCs MRP Line : @@IsSales

[!Line: UsCs MRP Line]


Add : Right Fields : At Beginning : UsCs MRP

The field is added in the beginning of right fields so that the column MRP is dis-
played prior to the Quantity field. The field is defined as follows
[Field: UsCs MRP]
Use : Rate Price Field
Width : 8
Align : Right
Border : Thin Left Right
Storage : UsCs MRP
Skip on : $$IsEnd:$StockItemName

2. The UDFs for storing the MRP values are defined as follows:
[System: UDF]
UsCs MRP : Rate : 5000
3. To capture the Length and Breadth details, a sub form is added.
From the default field VCHACC Stock Item, a sub form is displayed.

672
Use Cases

[#Field: VCHACC StockItem]


Add : SubForm : At Beginning : UsCs StkVCH Area : +
NOT $$IsEnd:$StockItemName
Appropriate storages are used in the fields as follows:
[Field: UsCs StkVCH Length]
Use : Number Field
Storage : UsCsStkLength
Align : Centre
Border : Thin Left Right

[Field: UsCs StkVCH Breadth]


Use : Number Field
Storage : UsCsStkBreadth
Align : Centre

The UDFs to store the Length and Breadth of an item are defined with appropri-
ate data type.
[System: UDF]
UsCsStkLength : Number : 101
UsCsStkBreadth : Number : 102
The calculation of dimension is specified in the field as follows.
[Field: UsCs StkVCH Dimension]
Use : Number Field
Skip : Yes
Set always : Yes
Set as : $UsCsStkLength * $UsCsStkBreadth
Format : "NoZero, NoComma"
Align : Centre
Border : Thin Left Right

673
Use Cases

The calculated area is set in the Quantity field. A method is added to the objects
Inventory Entry and the same is set in the Quantity fields Actual Qty and Billed
QTY.

[#Object: Inventory Entry]


UsCsStkArea: $UsCsStkLength * $UsCsStkBreadth

[#Field: VCH NrmlActualQty]


Set as: If Not $$IsEmpty:$UsCsStkArea then +
$UsCsStkArea else If @HasInvAlloc Then +
$$CollQtyTotal:BatchAllocations:$ActualQty+
Else @ResetVal

[#Field: VCH NrmlBilledQty]


Set as: If Not $$IsEmpty:$UsCsStkArea then $UsCsStkArea +
else If @HasInvAlloc Then $$CollQtyTotal:+
BatchAllocations:$BilledQty Else @ResetVal

[#Field: VCHBATCH NrmlAQty]


Set as: If Not $$IsEmpty:$$Owner:$UsCsStkArea then +
$$Owner:$UsCsStkArea else If $DiffActualQty +
then @ResetVal else $BilledQty

[#Field: VCHBATCH NrmlBQty]


Set As : If Not $$IsEmpty:$$Owner:$UsCsStkArea then +
$$Owner:$UsCsStkArea else If NOT $$IsEmpty +
:$$AltTable:VCHBATCHTrack:VCHBATCHOrder: +
$BilledQty AND ($$IsEmpty:$$Value) then @FinalBalVal
else @ResetVal

4. Further, a control is applied within the Quantity field so that the user can’t enter the
quantity, if it goes beyond availability.

674
Use Cases

Below are the code snippets shown for controlling Negative Stock along with the challenges
faced
Controlling the quantity by checking that the entered value is lesser than or equal
to the closing balance of the item as shown below:
[#Line: EI InvInfo]
Local : Field: VCHActualQty : Control : +
UsCs NegativeStock:$$Value > $ItemClBal +
AND @@IsOutwardType
Local: Field: VCHBilledQty:Control:UsCs NegativeStock +
:$$Value > $ItemClBal AND @@IsOutwardType

[#Object: Inventory Entry]


Item ClBal: $ClosingBalance:StockItem:$StockItemName

With the above method, we came across a loop hole. There was a possibility that
the user can select the same item in the current bill multiple times. In that case, vali-
dating only with the Item Closing Balance would not suffice. We also need to
include the quantities of the same Item entered above in the current bill. To do this,
the approach followed by us is to hold the entered Stock Items along with their
respective quantities in a list variable. The same is done using On Focus Event at
Line and User Defined Functions.as shown below:

[#Line: EI InvInfo]
On : Focus : Yes : CALL : UsCs Set List Variables : $$Line

The variable UsCs Item Var is defined as below:


[Variable: UsCs ItemVar]
Variable : UsCs OrigItem : String
Variable : UsCs OrigGodown: String
Variable : UsCs OrigQty: Quantity

The current Line number is passed as parameter to the function.

675
Use Cases

The function is defined with the parameter and local variable as follows:
[Function: UsCs Set List Variables]
Parameter: pLine : Number

Variable : LineKey: String


Variable : LineIndex: Number

The items in the List variable are added using a key. The key is a combination of
item name.

10 : SET : LineKey : $StockItemName

  The values are updated in the list variable “USCS ItemVar” based on the key
item name as follows:
100: SET : LineKey: #VCHStockItem
110: IF : NOT $$ListFind:UsCsItemVar:##LineKey
120: LIST ADD: UsCs ItemVar: ##LineKey
130: ENDIF
140: SET : LineIndex : $$ListIndex:UsCsItemVar:##LineKey
150: SET : UsCs ItemVar[##LineIndex].UsCs OrigItem: +
#VCHStockItem
160: SET : UsCs ItemVar[##LineIndex].UsCs OrigQty: if+
$$IsEmpty:##UsCsItemVar[##LineIndex].UsCsOrigQty+
then #VCHActualQty else if ##pLine = ##LineIndex+
then ##UsCsItemVar[##LineIndex].UsCsOrigQty else+
##UsCsItemVar[##LineIndex].UsCsOrigQty +
#VCHActualQty
170: ENDIF

Once the List Variables are updated with the values, the Quantity Field can be compared with
the current key combination entered quantity plus the closing balance for the current item.
Similarly, the same logic can be extended to the Batchwise supplementary form.

676
Use Cases

Section 2 : Invoice Customisation


1. The default form “Sales Color” is modified to specify the required invoice format. An
optional form is added in “Sales Color” for the same as follows:
[#Form: Sales Color]
Option: UsCs Global Sales Color: @@IsSales

2. The existing invoice format is removed and the report “UsCs Global Invoice” is used
to specify the required invoice format
[!Form: UsCs Global Sales Color]
Delete: Print
Add : Print: UsCs Global Invoice

3. The report UsCs Global Invoice is designed as per the given format.
 The default report Printed Invoice is used. The existing form is removed and a
new form is added in the report.
[Report: UsCs Global Invoice]
Use : Printed Invoice
Delete: Form
Add : Form: UsCs Global Invoice

In the form Page Break is specified at the form level as follows:
[Form: UsCs Global Invoice]
Use : STD Invoice Dimensions
|
Page Break: UsCs GI ClPgBrk, UsCs GI OpPgBrk
The company name is printed using @@CmpMailName.
 The voucher information like Party name, Voucher number, shipping details etc
is printed using the methods like $PartyLedgerName, $VoucherNumber, $ Basic-
ShippingDate etc.
To print the billing address line is repeated over the Address collection

Repeat : UsCs Global Invoice BillAdd : Address


The line is repeated over the collection Inventory Entries to print the Stock Item
details.

677
Use Cases

Repeat : UsCs GI Inventory Details: Inventory Entries


The methods $StockItemName, $BilledQty, $Rate etc are used to fetch the item
details.
The subtotals are displayed using the collection function $$CollAmtTotal

$$CollAmtTotal:InventoryEntries:$Amount
 A line is repeated over a collection to display the company address and the col-
lection is defined as follows:
Repeat: UsCs GI Address: UsCs Company Address

[Collection: UsCs Company Address]


Type : Address : Company
Child of : ##SVCurrentCompany
Fetch : Address
  The other company details like Phone number, email address etc are printed
using the following method syntax:
$PhoneNumber:Company:##SVCurrentCompany

678
References and Bibliography

http://www.tallysolutions.com/website/html/developernetwork/developernetwork-over-
view.php
http://www.tallysolutions.com/website/html/developernetwork/tallydefinitionlanguage.php
http://www.tallysolutions.com/website/html/developernetwork/whats-new.php
http://www.tallysolutions.com/website/html/downloads/tally-development-environment.php
http://www.tallysolutions.com/tallyweb/modules/operation/extranet/
CXTD9DownloadViewMgr.php
http://www.tallysolutions.com/website/html/developernetwork/integration-capabilities.php

Vous aimerez peut-être aussi