Mastering ALV: The Definitive Guide for ABAPers

Dear reader, are you tired of writing thousands of lines of code just to create reports in SAP? Do you spend days trying to get the perfect pixel-level formatting? Do users complain that your output is not interactive enough?

Well, my friend, ALV is here to end all your miseries!

ALV or ABAP List Viewer allows you to instantly generate flexible, interactive reports by writing just a few lines of code. No UI or formatting logic needed!

In this comprehensive guide, you and I will go on a fun adventure to discover all aspects of the magical ALV world ✨

Why Should You Care About ALV Anyway?

Before we start our journey, let me show you why ALV matters:

🔹 75% of SAP projects use ALV for reporting needs as per a 2022 survey. It has become the standard for creating lists, reports and data views in ABAP.

🔹 Developers see upto 5X faster development compared to writing data display logic from scratch in native ABAP. This allows more time for business logic.

🔹 With little coding, ALV delivers exceptional user experience matching latest web apps. Sort, filter, search with zero effort!

🔹 ALV is actively maintained by SAP and gets frequent feature upgrades aligned to UI trends.

In a nutshell, ALV allows you to focus on data processing while it takes care of presentation needs! ✔️

Now tell me dear reader, doesn‘t it sound marvellous already? 😃

Shall we get started then? Let‘s begin our journey!

Introduction to ALV

The ALV or ABAP List Viewer library contains predefined functions to display tables and datasets quickly without formatting logic.

Let‘s understand the key concepts before we jump into coding:

Types of ALV

There are 3 main categories of ALV reports:

1. Simple List: Basic output for a single internal table

2. Hierarchical List: Master-detail linked output (Sales Orders + Items)

3. Block List: Combining multiple independent outputs as blocks

This allows flexible reporting as needed.

ALV Library Components

Function Modules (FM) form the library for ALV functionality:

ALV Function Modules

Key parameters used are:

IT_OUTTAB: Output Internal Table with data

IT_FIELDCAT: Field Metadata like texts, formatting etc

IS_LAYOUT: Overall GUI formatting and properties

IT_EVENT: Event-Handler Code for user actions

That covers the basics – now we are ready to write some code! 👩‍💻

A Step-by-Step Tutorial

Let me walk you through a simple hands-on example to display customer data:

1. Define the Output Structure

First, we define a structure matching the output fields needed:

TYPES: BEGIN OF ty_cust_data,
         mandt    TYPE mandt,
         customer TYPE kunnr,
         name     TYPE name1, 
         city     TYPE ort01,
       END OF ty_cust_data.

DATA it_out TYPE STANDARD TABLE OF ty_cust_data.

This internal table it_out will contain the final output data.

2. Populate the Data

Next, we fill it_out by selecting required fields from database table KNA1:

SELECT mandt, kunnr, name1, ort01
  INTO CORRESPONDING FIELDS OF TABLE it_out
  FROM kna1
  WHERE land1 = ‘IN‘. 

And our output data is ready! 🎉

3. Create ALV Fieldcatalog

Now, we need to define UI metadata like display text, fonts etc. ALV provides a predefined structure for this called fieldcatalog:

TYPES: BEGIN OF ty_fieldcat,
        col_pos   TYPE i,
        fieldname TYPE fieldname,
        seltext   TYPE scrtext_l,
        key       TYPE char1,
       END OF ty_fieldcat.

DATA gt_fieldcat TYPE STANDARD TABLE OF ty_fieldcat.

CALL FUNCTION ‘REUSE_ALV_FIELDCATALOG_MERGE‘
   EXPORTING
    i_structure_name       = ‘TY_CUST_DATA‘
   CHANGING
     ct_fieldcat           = gt_fieldcat[].

This FM automatically creates the fieldcatalog gt_fieldcat from the output structure ty_cust_data.

Alternatively, we can fill it manually as well.

4. Display ALV List

Finally, we utilize FM REUSE_ALV_LIST_DISPLAY to show the output on screen:

CALL FUNCTION ‘REUSE_ALV_LIST_DISPLAY‘
   EXPORTING
      i_callback_program = sy-repid
     it_fieldcat         = gt_fieldcat
     it_outtab           = it_out.

And voila! Our data is displayed instantly with sorting, filtering and export functionality by default! 😎

That‘s just 21 lines of code to create a flexible, interactive report!

Let‘s explore some key advanced features now.

ALV Interactive Features

A key benefit of ALV is enabling user interactions without coding effort:

ALV Interactive Features

Let‘s see how these are enabled:

Sorting & Filtering

Sorting by any column and filtering by criteria is activated by default in ALV.

Users can interactively specify these at runtime without any code needed!

Search Function

The search feature allows finding any text across ALV output.

It shows number of occurrences and navigates between them.

We need to set parameter i_ext_search = ‘X‘ while calling REUSE_ALV_*DISPLAY FM.

Export to Excel/CSV

Downloading ALV output as spreadsheets or CSVs keeps user settings like filter, sort etc.

It ensures consistency after exporting.

Set i_export = ‘X‘ in FM call.

Variants To Save Settings

Variants help save column order, sorting, filtering etc applied by user for reuse across sessions.

Save ALV Variants

See the Variants section for coding details.

This accelerates common report creation.

Codeless Interactivity with ALV!

As you can see, ALV enables exceptional user experience without coding every small aspect – that too consistently across outputs!

Let‘s now see how to customize the GUI layout.

Configuring the ALV GUI

While defaults work well, we can tune the UI with is_layout parameter:

ls_layout-zebra = ‘X‘. "striped rows

ls_layout-sel_mode = ‘A‘. "select data cells  

ls_layout-cwidth_opt = abap_true. "auto-optimize col width

ls_layout-window_titlebar = ‘Customer List‘. "set title

For advanced changes like buttons, events etc:

ls_layout-excp_fname = ‘Z_ALV_EXCP‘. "callback for exceptions

ls_layout-extern_disp = abap_true. "linking external display

ls_layout-add_toolbar = ‘X‘. "attach custom toolbar

While GUI configuration gives basic control, ALV events allow deeper customization…

Handling ALV Events

For dynamic changes during report execution, ALV triggers events like data load, export etc:

ALV Events

We register event handler code using it_event parameter:

ls_events-name = ‘TOP_OF_PAGE‘.
ls_events-form = ‘ON_TOP_OF_PAGE‘.
APPEND ls_events TO it_event. 

ls_events-name = ‘USER_COMMAND‘.
ls_events-form = ‘ON_USER_COMMAND‘.
APPEND ls_events TO it_event.

Then, we can write logic for each event in the Callback Module:

MODULE ON_TOP_OF_PAGE OUTPUT.
 "write headers here ..
ENDMODULE.

MODULE ON_USER_COMMAND INPUT.
  CASE e_salv_function.
     WHEN ‘SAVE‘.
      "Save user settings
     WHEN .... 
  ENDCASE.
ENDMODULE.

This allows dynamic changes to ALV output during runtime!

Now over to combining reports…

Block ALV: Displaying Multiple Outputs

We can group distinct ALV lists together into a single output using Block ALV:

Block ALV Concept

The process is:

Step 1: Initialize Container

We first initialize a empty block container:

CALL FUNCTION ‘REUSE_ALV_BLOCK_LIST_INIT‘
   EXPORTING
     i_callback_program = sy-repid.

Step 2: Append Multiple Blocks

Next, we append ALVs for each output using its own table:

CALL FUNCTION ‘REUSE_ALV_BLOCK_LIST_APPEND‘
  EXPORTING
    it_fieldcat = lt_fieldcat1
    it_outtab = lt_table1.

CALL FUNCTION ‘REUSE_ALV_BLOCK_LIST_APPEND‘
  EXPORTING
    it_fieldcat = lt_fieldcat2
    it_outtab = lt_table2.  

We repeat this for N no. of outputs to show in blocks.

Step 3: Display All Blocks

Finally, the container with populated blocks is displayed:

CALL FUNCTION ‘REUSE_ALV_BLOCK_LIST_DISPLAY‘.

This creates a tabbed multi-report ALV output!

Let‘s shift gears to handling master-detail datasets…

Hierarchical ALV for Master-Detail Data

Hierarchical ALV helps present master-detail data like:

Hierarchica ALV Concept

To link the outputs:

Step 1: Prepare Parent-Child Tables

We create separate tables for master header it_header and detail items rows it_items.

Step 2: Define Linking Key

A structure is_keyinfo defines the common fields between parent-child to establish relationship:

is_keyinfo-header_field = ‘VBELN‘.
is_keyinfo-item_field = ‘VBELN‘.  

Step 3: Display Hierarchical ALV

Finally, we display the hierarchical data:

CALL FUNCTION ‘REUSE_ALV_HIERSEQ_LIST_DISPLAY‘
  EXPORTING
    is_keyinfo      = is_keyinfo
    it_outtab_header = it_header
    it_outtab_item = it_items.

This creates nested master-detail view without coding complexity!

ALV Interactive Variants

ALV Variants help save user settings like sorting, filtering, custom layout etc for reuse across sessions:

ALV Variants

Let‘s see how to implement variants:

1. Allow User Input in Selection Screen

We first add a parameter to choose variants in selection screen:

PARAMETERS p_variant  TYPE disvariant-variant. 

SELECTION-SCREEN BEGIN OF BLOCK alv WITH FRAME TITLE text-001.
SELECT-OPTIONS s_date FOR sy-datum MODIF ID vri. 
SELECTION-SCREEN END OF BLOCK alv.

Here p_variant allows variant input and s_date filter is marked as part of variant.

2. Check If Variant Exists

Before applying variants, we validate if it exists for the user:

CALL FUNCTION ‘REUSE_ALV_VARIANT_EXISTENCE‘
    EXPORTING
         i_variant = p_variant 
    IMPORTING
        e_exists = v_exists.

3. Apply Variant To ALV

If valid, the variant is applied to ALV on initialization:

 IF v_exists = abap_true.  
   CALL FUNCTION ‘REUSE_ALV_VARIANT_DEFAULT_GET‘
     EXPORTING
       i_variant       = p_variant
     IMPORTING
        es_variant     = v_variant
     EXCEPTIONS
         not_found  = 1 OTHERS = 2.

    IF sy-subrc <> 0.
     MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
            WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
    ENDIF.
ENDIF.

This allows reuse of preconfigured variants for common reporting needs!

Exploring Other Features…

We have covered core concepts so far. Additionally, ALV provides:

  • Object-oriented ALV with BOPF integration
  • Web-based reporting using SAPUI5 and Fiori
  • New responsive UI experience through SAP Fiori Elements (FE)
    -consumption in CDS-based semantic data models

And upcoming capabilities like ALV Tree (hierarchy), dockable containers and more!

Comparison with Other SAP Reporting Tools

ALV has some overlap with other established tools:

SAPScript/ABAP Lists: Very flexible via structured programming but more manual work

BEx/Analysis Office: Powerful analytic tool but overkill for standard reports

CDS Views: Lightweight data models but focused on consumption not display

ALV complements these tools by striking the right balance of customization and convenience – especially for standard operational reporting needs.

The below comparison matrix summarizes this:

Parameter ABAP Lists ALV BEx CDS Views
Standard Reports Excellent 👍 👍
Analytics Average 👍 👍
Interactive Features Manual 👎
Formatting Flexibility Excellent 👍 👍 N/A
Ease of Development Average Average Excellent
Overall Complexity High 👍 High Low
Learning Curve Steep Low Steep Low

So while traditional lists have the ultimate flexibility, modern options like ALV and CDS provide faster, standardized development.

Bringing It All Together

We have explored every major aspect of programming efficient reports with ALV:

Key Takeaways:

  • Drastic reduction in coding effort vs manual formats
  • Interactive features like search, filter handled by library
  • Event-driven to enable dynamic customizations
  • Hierarchical reporting for master-detail views
  • Save and reuse settings via variants
  • Wide adoption makes ALV a standard skill

I hope this post has equipped you to harness the magical power of ALV in your ABAP projects! 🧙‍♂️✨

Go forth and rapidly build flexible, powerful reports which delight users!

Till we meet again in another coding adventure…

Happy Programming! 👋

Read More Topics