alv (fiche technique)

108
Documentation sur L’ABAP List Viewer VERSION 3.1 ALV PAGE 1 / 108

Upload: sto4000

Post on 07-Mar-2015

1.326 views

Category:

Documents


10 download

TRANSCRIPT

Page 1: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

ALV

PAGE 1 / 92

Page 2: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

SOMMAIRE : ALV .........................................................................................................................................................................1

..................................................................................................................................................................................1

SOMMAIRE :..........................................................................................................................................................2

A Introduction :Comment devenir super fort pour faire des listes ........................................................................3

B Réalisation technique ALV STANDARD:...........................................................................................................4

C Utilisation des fonctions ALV définies pas SAP................................................................................................45

D ANNEXES :........................................................................................................................................................69

E Annexe sur ALV standard..................................................................................................................................72

TO DO :................................................................................................................................................................92

PAGE 2 / 92

Page 3: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

A Introduction :Comment devenir super fort pour faire des listes NOTA : Cette documentation présente l’implémentation d’une ALV dans un programme en utilisant les fonctions de base fournis par SAP, dans de nombreux cas simple on peut utiliser certaines fonctions standard fournit par SAP. (voir annexe)

A.I Introduction

Afin de générer des listes qui soient enfin attractives, interactives et amusantes, SAP a développé un outil efficace : l’Abap List Viewer. Il s’agit, en vérité, d’un objet de R/3 version.4.6, exploitable dans les développements spécifiques, pour qui veut bien s’arrimer aux exemples abscons délivrés par la maison mère.Pour les profanes, l’intégration de la programmation objet dans SAP, peut s’avérer fastidieuse. En effet, la gestion de méthodes, ‘class’, et autres ‘public section’, demande une étude approfondie et une implication coûteuse en temps. Aussi, il convient de présenter le résultat de ces investigations en s’orientant principalement vers l’opérationnel. Les esthètes de la programmation objet voudront bien pardonner au néophyte, les approximations et contre sens qui ne sauront manquer d’émailler la présentation.

A.II Fondements théoriques.

L’affichage d’une liste par ALV, se base sur l’utilisation d’un objet le CL_GUI_ALV_GRID. Il faut définir un catalogue qui référence et spécifie les caractéristiques des cellules d’affichage. Il s’agit donc d’une table interne de 60 champs, qui chacun décrit un attribut de la cellule. Parmi ceux-ci, on trouvera le champ fieldname qui reprend le nom du champ de la table interne souhaité dans la cellule. Les autres font varier des caractéristiques d’affichage tel que la position de la colonne, sa taille, la gestion en checkbox, etc.…Cette table interne doit reprendre strictement le format de la table interne à afficher, cela signifie que chaque champ doit être retrouver en tant que valeur dans le champ ‘fieldname’ de la table catalogue. Une table de lay-out, permettra de gérer un certain nombre de caractéristiques graphiques sur la structure d’entête de colonne, comme empêcher d’effectuer des totaux sur la colonne (par rapport au fieldname), affichage de l’en-tête de colonne en hot-spot..En l’état, il est dès lors possible d’afficher la table souhaitée à l’écran…. pour peu que les récepteurs adéquats aient été installés dans l’écran appelé. En effet, un objet de type ‘custom control’ devra avoir été installé comme réceptacle de la liste dans l’écran appelé. Les fonctions standards de l’ALV telles que le tri, le filtre, l’export sous Excel, les Totaux, les Sous totaux, etc.. seront alors automatiquement gérées.D’autres fonctionnalités peuvent alors être implantées, dans un menu spécifique afin de gérer une interaction.

La mise en place de cette technique semble nécessiter des connaissances particulièrement poussées de la programmation objet. Il n’en est rien. Vaguement imprégné de ce qui précède, il est possible d’effectuer exactement le même travail en utilisant astucieusement et uniquement des ‘call function’ adéquats.

PAGE 3 / 92

Page 4: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

B Réalisation technique ALV STANDARD:

B.I Présentation Générale :

B.I.1 Schéma général

La réalisation d’un programme sous sap utilisant l’ALV comme outil de report est relativement simple, cependant un certain nombre d’étapes sont indispensable.

(Il existe au sein de SAP des fonctions standards permettant de réaliser en très peu d’étape l’affichage d’une liste, cependant les possibilités de personnalisation (en particulier pour les évènements) sont alors plus réduites. Une de ces fonctions est décrite en annexe.)

Le schéma suivant présente l’implémentation basique d’un report sous ALV.

CATALOGUE

CONTAINER DE RECEPTION

GRILLE ALV

LAYOUT

VARIANTE

Para m

ètre s :

EVENEMENT

Objet attaché :

CATALOGUE

CONTAINER DE RECEPTION

GRILLE ALV

LAYOUT

VARIANTE

Para m

ètre s :

EVENEMENT

Objet attaché :

EVENEMENT

Objet attaché :

B.I.2 Définition des différentes éléments:

B.I.2.A ECRAN – SCREEN PAINTER

L’affichage d’un composant ALV demande en premier lieu, qu’un écran soit définit par l’intermédiaire du screen painter (transaction se51). Au sein de ce dernier on insérera un objet « custom contrôle », lequel recevra par la suite la grille ALV et limitera la taille à afficher. (Une méthode est présentée en annexe permettant d’utiliser une grille ALV sans utiliser le SCREEN PAINTER)

B.I.2.B CONTAINER

Ce dernier est utilisé pour accueillir le composant ALV, il doit faire référence à un custom contrôle définit dans un écran (Voir screen painter).

PAGE 4 / 92

Page 5: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

B.I.2.C GRILLE ALVCe composant correspond à la grille que l’on souhaite afficher, il existe un nombre important de paramètres disponibles afin de modifier son comportement. Les trois principaux paramètres à fournir sont :

1. Variante.2. Layout.3. Catalogue

B.I.2.D CLASSE DES ÉVÈNEMENTS :Celle-ci contient l’ensemble des fonctions définis par l’utilisateur et le comportement

associé : double clic, bouton, sélection…

B.I.2.E CATALOGUE : Ce dernier correspond à une table interne et définit entièrement les informations

relatives à l’affichage des champs dans l’ALV.

PAGE 5 / 92

Page 6: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

B.II L’écran – le screen painter

NOTA : Cette opération est très simple, mais n’est pas obligatoire. Il est possible d’utiliser des containers totalement autonome : voir annexe.

Afin de créer un écran contenant un objet « custom contrôle », il faut appeler la transaction SE51.

Au sein de cette dernière on définit le nom du programme générant les données ainsi que le numéro de l’écran qui sera appelé.Et ensuite appuyer sur le bouton CREER.

Remplir les paramètres de l’écran suivant :

Une fois l’écran créer, il faut alors le modifier selon notre objectif :

PAGE 6 / 92

Page 7: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

Sélection le bouton (custom controle) puis le placer sur la partie de gauche tout en le dimensionnant enfin il faut lui définir un nom.

Nota :Une bonne taille pour un affichage classique semble être :

140 pour la longueur visible 40 pour la hauteur 1 pour les minimums des lignes et colonnes redimensionnables

OK_CODE .Afin de pouvoir utiliser un ok_code, il est indispensable de le définir dans la liste des éléments :(variable de type OK) et dans le programme appelant l’ALV avec le même nom.

IL suffit alors d’activer.

PAGE 7 / 92

Custom contrôle Nom de l’objet

Page 8: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

B.III Le catalogueAide SAP : SAP Library

Basis componentsBasis services / communication interface (BC-SRV)

Abap list viewer (BC-SRV-ARL)BC-ALV Grid Control

B.III.1 DéfinitionLors de la création du composant ALV, un ensemble de paramètres sont fournit tels le catalogue. Celui-ci est une table de type LVC_T_FCAT qui contient toutes les informations sur les champs à afficher :

Intitulé de colonne Tooltips Taille Position Autres

Il existe plusieurs moyens de générer ce catalogue:

Automatique Manuel Semi-automatique

La méthode manuelle permet de définir à la main la totalité des champs nécessaire.

B.III.2 Méthode automatique :Si la structure de la table contenant les données est issue du dictionnaire, la définition du catalogue est alors automatiquement faite lors de la création de l’ALV. Tous les champs de la structure sont alors affichés. Voir section sur le composant ALV.

B.III.3 Méthode manuelleTous les champs à afficher dans l’ALV peuvent être définit manuellement en utilisant un type (DEC, CHAR…) ou une référence à un champ d’une table du dictionnaire.L’objectif est alors de créer une table interne de type LVC_T_FCAT.

B.III.3.APROCESSUS :

1. Déclaration de la table interne :Data : GT_FIELDCAT TYPE LVC_T_FCAT WITH HEADER LINE.

2. Ajout des champs 1 à 1.Lors de l’ajout d’un champ dans le catalogue, on peut soit, lorsque cela est possible faire référence à un champ d’une table du dictionnaire soit définir entièrement les caractéristiques du champ.

Référence :REF_FIELD Correspond au nom du champ de référence.

Ex ‘NAME1’REF_TABLE Correspond à la table de référence.

Ex ‘KNA1’

PAGE 8 / 92

Page 9: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

Les intitulés sont alors directement récupérés et ne peuvent pas être modifiés.

Spécifique: 

TEXTECOLTEXT Intitulé de la colonneTOOLTIP Intitulé de la bulle d’aideSELTEXT Intitulé du texte

Définition du champ :DATATYPE ou INTTYPE

DATATYPE Type de donnée : DEC, CHARINTTYPE Type de donnée élémentaire C, I

OUTPUTLEN Largeur de la colonne

Il peut être utile dans le cas de champs spécifique d’utiliser des routines de conversion d’entrée-sortie. On utilise alors le champ

EDIT_MASK

If you set a conversion exit (for example, conv = ' ==ALPHA ' for function module CONVERSION_EXIT_ALPHA_OUTPUT ), you enforce output conversion for the associated output field. (See also F1 help for WRITE edit option USING EDIT MASK) .

Commun : Nom du champ DésignationFIELDNAME Référence à la table interne contenant les données

KEY Clé (si la valeur ‘X’ est fourni alors la colonne sera affichée à gauche de l’ALV et sera figée par rapport aux déplacements horizontaux)

COL_POS Position de la colonne.

B.III.3.BEXEMPLE DE CRÉATION DU CATALOGUE

DATA : GT_FIELD_CAT_POSTE type LVC_T_FCAT with header line, POS TYPE I VALUE 1.

CLEAR : POS , GT_FIELD_CAT_POSTE.

GT_FIELD_CAT_POSTE-COL_POS = POS. GT_FIELD_CAT_POSTE-FIELDNAME = 'VRKME'. GT_FIELD_CAT_POSTE-tabname = 't_poste'. GT_FIELD_CAT_POSTE-ref_field = 'VRKME'. GT_FIELD_CAT_POSTE-REF_TABLE = 'VBRP'. GT_FIELD_CAT_POSTE-KEY = 'X'. APPEND GT_FIELD_CAT_POSTE.

CLEAR GT_FIELD_CAT_POSTE. POS = POS + 1.

GT_FIELD_CAT_POSTE-COL_POS = POS. GT_FIELD_CAT_POSTE-FIELDNAME = 'Z_FKIMG'. GT_FIELD_CAT_POSTE-tabname = 't_poste'. GT_FIELD_CAT_poste-coltext = 'QTE en UR'. GT_FIELD_CAT_poste-seltext = 'Quantité facturé en unité de référence'. GT_FIELD_CAT_POSTE-DATATYPE = 'QUAN'. GT_FIELD_CAT_POSTE-OUTPUTLEN = '3'. APPEND GT_FIELD_CAT_POSTE.

PAGE 9 / 92

Page 10: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

B.III.4 Méthode semi-automatique

Si on génère le catalogue de façon semi-automatique, on peut utiliser des champs issus du dictionnaire mais aussi spécifiques. Il est alors aussi possible de modifier ou d’ajouter des champs.

Par exemple si on souhaite afficher une structure du dictionnaire sans pour autant afficher toutes les colonnes, on peut alors soit utiliser le champ ‘NO_OUT’ dans la structure du catalogue, soit effacer l’enregistrement.

(voir LVC_T_FCAT)

B.III.4.APROCESSUS :

1. Déclarer une table interne du type LVC_T_FCAT .

Data : GT_FIELDCAT TYPE LVC_T_FCAT WITH HEADER LINE.

2. Appeler la fonction LVC_FIELDCATALOG_MERGE et donner en argument

la structure de la table contenant les données à afficher la table interne correspondant au catalogue

3. Ajout de champs spécifiques  se fait alors manuellement :

Nom du champ Exemple de valeur DésignationCLEAR GT_FIELDCAT.GT_FIELDCAT-FIELDNAME = 'ECART'. Nom du champGT_FIELDCAT-COL_POS = '12'. Position de la colonne dans l’ALVGT_FIELDCAT-COLTEXT = 'ECART.'(100). Intitulé de la colonneGT_FIELDCAT-TOOLTIP = 'ECART.'(101). Intitulé de la Bulle d’aideGT_FIELDCAT-SELTEXT = 'ECART.'(102). Intitulé de la colonne lors d’un

passage de la sourisGT_FIELDCAT-DATATYPE = 'DEC'. Type de donnée (Pour les données

de base on utilise le champ INTTYPE)

GT_FIELDCAT-OUTPUTLEN = 13. Taille de la colonne en sortieAPPEND GT_FIELDCAT.

4. Il est alors possible de lire la table et de modifier les différents paramètres. Il n’est par contre pas possible de modifier les intitulés des colonnes générées automatiquement à partir du dictionnaire.

B.III.5 Exemple* On initialise le catalogue.clear gt_fieldcat.refresh gt_fieldcat.

* Appel de la fonction afin de générer un catalogue* a partir de la table ZINV définit dans le dictionnaire

CALL FUNCTION 'LVC_FIELDCATALOG_MERGE' EXPORTING I_STRUCTURE_NAME = 'ZINV' CHANGING CT_FIELDCAT = gt_fieldcat[].

* Exemple de suppression delete gt_fieldcat where fieldname = 'UZEIT'.

* Exemple de modification READ TABLE GT_FIELDCAT WITH KEY FIELDNAME = 'WERKS'.

PAGE 10 / 92

Page 11: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

IF SY-SUBRC = 0. GT_FIELDCAT-COL_POS = '1'. MODIFY GT_FIELDCAT INDEX SY-TABIX. ENDIF.

* Exemple d’ajout de champ spécifique

CLEAR GT_FIELDCAT. GT_FIELDCAT-FIELDNAME = 'QSTSA'. GT_FIELDCAT-COL_POS = '8'.* GT_FIELDCAT-SYMBOL = 'X'. GT_FIELDCAT-COLTEXT = 'STOCK SAP'(100). GT_FIELDCAT-TOOLTIP = 'STOCK SAP'(101). GT_FIELDCAT-SELTEXT = 'STOCK SAP'(102). GT_FIELDCAT-DATATYPE = 'DEC'. GT_FIELDCAT-OUTPUTLEN = 13. APPEND GT_FIELDCAT.

B.III.6 Catalogue – Quantité et currency

B.III.6.AGESTION DES DEVISES : (VOIR DOC SAP)

Dans le cas, où l’on affiche des valeurs nécessitant un formatage selon une devise, on peut :

o Soit utiliser le champ CURRENCY pour une devise fixe pour toute la colonne.o Soit CFIELDNAME faisant référence à un autre champ (de type devise telles que DEM ou USD) du

Catalogue.

B.III.6.BGESTION DES QUANTITÉS : (VOIR DOC SAP)

Dans le cas, où l’on affiche des valeurs nécessitant un formatage selon une quantité, on peut :

o Soit utiliser le champ QUANTITY pour une devise fixe pour toute la colonne.o Soit QFIELDNAME faisant référence à un autre champ (de type unit tel que KG) du Catalogue.

PAGE 11 / 92

Page 12: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

B.IV Le container

Le container est l’objet qui doit contenir le composant ALV. Celui-ci fait appel à un container crée au préalable dans un screen.La déclaration du container se fait de préférence au début du programme.Dans notre exemple “BCALVC_TOOLBAR_D100_C1” correspond au nom de l’objet ‘custom controle’ dans l’écran de sélection.

B.IV.1 Paramètres :cont_on_main doit contenir le nom du « custom contrôle»

* Déclaration du containerDATA custom_container1 TYPE REF TO cl_gui_custom_container,* Nom du Container de référence = 'BCALVC_TOOLBAR_D100_C1' cont_on_main TYPE scrfname VALUE 'BCALVC_TOOLBAR_D100_C1'

.

*Dans le PBO   !

* Création de l’objet container* create a custom container control for our ALV Control IF custom_container1 is initial. CREATE OBJECT custom_container1 EXPORTING container_name = cont_on_main “ Nom du Container de référence EXCEPTIONS cntl_error = 1 cntl_system_error = 2 create_error = 3 lifetime_error = 4 lifetime_dynpro_dynpro_link = 5. IF sy-subrc ne 0. CALL FUNCTION 'POPUP_TO_INFORM' EXPORTING titel = g_repid txt2 = sy-subrc txt1 = 'The control could not be created'(510). ENDIF.Endif.

PAGE 12 / 92

Page 13: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

B.V Gestion du layout La structure du layout contient un ensemble de champs permettant de configurer les propriétés graphiques de la grille ALV. Cette structure est de type : LVC_S_LAYO.

B.V.1 Options principales

Nom du champ DésignationGrid_title Défini le titreSel_mode Sélection de multi-ligneCWIDTH_OPT Ajuste la taille des colonnes selon le contenu.NO_TOOLBAR Permet de ne pas afficher la barre des boutons

Exemple :

*Déclaration Data : gs_layout TYPE lvc_s_layo.* Titre gs_layout-grid_title = 'Listes des factures'(100).

* allow to select multiple lines gs_layout-sel_mode = 'A'.

* Ajuste la taille des colonnes gs_layout-cwidth_opt = 'X'.

B.V.2 Gestion des couleurs

B.V.2.A GESTION DE COLONNE EN COULEUR

Dans le catalogue

EMPHASIZE LVC_EMPHSZ Char(4) SPACE, 'X' or 'Cxyz' (x:'1'-'9'; y,z: '0'=off '1'=on)

If the field is set to 'X', the ALV uses a pre-defined color for highlighting the column. If the character field begins with 'C' (color code), the remaining numbers have the following meaning:

x: color number

y: intensified display on/off

y: inverse display on/off

For more information on color coding, see the F1 help on the FORMAT statement.

B.V.2.B GESTION DE LA COULEUR POUR LES LIGNES.1 Il faut ajouter un champ caractère de taille 4 à la table contenant les données, et lui affecter la couleur à afficher.

DATA: BEGIN OF GT_OUTTAB OCCURS 0.

INCLUDE STRUCTURE <DDIC-Struktur>.

DATA: linecolor(4) type c. "Color for corresponding line

DATA: END OF GT_OUTTAB.

PAGE 13 / 92

Page 14: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

2 Renseigner le champ INFO_NAME de la structure.

GT_CATALOG-INFO_NAME = linecolor.

B.V.2.C GESTION DE LA COULEUR POUR DES CELLULES

Ajouter une table des couleurs du type LVC_T_SCOL à la table contenant les données à afficher :

DATA: BEGIN OF GT_OUTTAB OCCURS 0.

INCLUDE STRUCTURE SFLIGHT.

DATA: CT TYPE LVC_T_SCOL. "Table for colors

DATA: END OF GT_OUTTAB.

La table de type LVC_T_SCOL des couleurs contient 3 champs

FNAME Contrôle ALV : nom de zone de table interne

COLOR Contrôle arbre ALV : codage couleur

NOKEYCOL Contrôle ALV : substituer la couleur de la clé

Si le champs NOKEYCOL est égal à ‘X’ alors il est possible de changer la couleur des champs clé définit dans l’ALV (Voir le catalogue).

Si on veut colorer la ligne, il suffit de définir la couleur souhaitée dans le champ COLOR et ne pas affecter le champs FNAME.

Si on veut affecter plusieurs cellule il faut mettre le nom de la colonne dans le champs FNAME. Si on souhaite colorer plusieurs cellule, il faut alors ajouter plusieurs lignes dans la table.

Enfin il faut assigner le nom de la table interne (pour notre exemple CT) dans le champ CTAB_FNAME de la structure layout.

B.V.2.D AFFICHAGE ZÉBRÉ DES LIGNES

Dans la structure layout :

ZEBRA If this field is set, the list shows a striped pattern in the print preview and when it is printed.

SPACE, 'X'

PAGE 14 / 92

Page 15: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

B.VI Gestion variantes

L’ALV offre la possibilité de gérer l’utilisation de variantes définissant les colonnes affichées et autres aspects graphiques. Cependant il incombe au développeur de gérer les propriétés que peuvent prendre les variantes. Pour ce faire, ce dernier dispose de 3 paramètres :

I_SAVE IS_VARIANT I_DEFAULT

Mode Result Values of I_SAVE and

IS_VARIANT when

set_table_for_first_display is called

Changing the current display variant only

The ALV grid control displays only the variant icon ( ) but no menu in the toolbar. By clicking this icon, users can change the current display variant (basically, they can modify the selection and the order of the columns displayed).

IS_VARIANT = SPACE.

I_SAVE = SPACE.

(default setting)

Loading delivered display variants only

The ALV grid control displays both the variant icon and a menu in the toolbar. The menu contains only functions for selecting and changing display variants.

IS_VARIANT = <variant structure>

I_SAVE = SPACE .

(or IS_VARIANT is SPACE and I_SAVE is not SPACE )

Loading and saving display variants

The ALV grid control displays both the variant icon and a menu in the toolbar. By clicking this icon, users can select an existing display variant. The menu provides functions for selecting, changing, saving and managing display variants.

IS_VARIANT = <variant structure>

I_SAVE = <'X', 'U' or 'A'>

See also: Saving Display Variants

Par défaut l’utilisateur peut saisir des variantes, ces dernières ne sont pas rappelées lors des utilisations futures. Par contre, si l’utilisateur ne doit pas avoir accès à l’utilisation de variantes, il suffit de définir la valeur ‘SPACE’ pour I_DEFAULT .Les possibilités offertes pour la gestion des variantes sont importantes et sont définis par l’intermédiaire de paramètres.Le premier paramètre à utiliser est de type DISVARIANT.

Data :GS_VARIANT TYPE DISVARIANT. 

ce dernier doit contenir au minimum l’ID du programme  dans le champ REPORT:

G_REPID = SY-REPID.GS_VARIANT-REPORT = G_REPID.

PAGE 15 / 92

Page 16: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

Un second paramètre permet de déterminer les options de sauvegarde :

DATA : X_SAVE type c.

X_SAVE = SPACE Variants cannot be saved.

X_SAVE = 'U' Only user-defined variants can be saved.

X_SAVE = 'X' Only global variants can be saved.

X_SAVE = 'A' Both user-defined and global variants can be saved.

Example:

* Déclaration

Data : gs_variant TYPE disvariant,

x_save value 'A',

g_repid like sy-repid.

clear gs_variant.

* 'gs_variant' must at least contain the report-id to allow

* saving a variant.

g_repid = sy-repid.

* § 2.At least field REPORT of this structure has to be filled!

gs_variant-report = g_repid.

NOTA :

Afin de gérer les variantes selon les dynpros, il est utile de définir le champ HANDLE

STRUCTURE DISVARIANT

REPORT Nom du programme ABAP

HANDLE ID de gestion pour appel répété depuis le même programme

LOG_GROUP Clé de groupe logique

USERNAME Nom utilisateur pour mémorisation personnalisée

VARIANT Variante d'affichage

TEXT Désignation variante affichage

DEPENDVARS Vecteur entrées de var. dépendantes

PAGE 16 / 92

Page 17: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

B.VII Les évènements

Outres la simplification de la gestion de l’affichage, l’utilisation de L’ALV offre aussi la possibilité de gérer un ensemble d’évènements.

B.VII.1 Définition :La première étape consiste à créer une classe permettant de définir ses propres fonctions (METHOD) :NOTA : Si la classe n’est pas définit au tout début du programme, toute référence à la classe ne pourra être faites qu’après. Pour palier à ce problème on inclut la ligne de code suivante :

* Predefine a local class for event handling to allow the* declaration of a reference variable before the class is defined.CLASS lcl_event_receiver DEFINITION DEFERRED.

Exemple de définition :

***************************************************************** LOCAL CLASSES: Definition*****************************************************************===============================================================* class lcl_event_receiver: local class to* define and handle own functions.** Definition:* ~~~~~~~~~~~class lcl_event_receiver definition.

public section.

methods: handle_toolbar for event toolbar of cl_gui_alv_grid importing e_object e_interactive ,

handle_user_command for event user_command of cl_gui_alv_grid importing e_ucomm,

handle_double_click for event double_click of cl_gui_alv_grid importing e_row e_column.

data : poste type c value 'P'.

private section.

endclass.** lcl_event_receiver (Definition)*===============================================================

La définition d’une fonction rattachée à un événement est très simple : handle_toolbar -> nom de la fonction double_click -> Nom de l’évènement (voir annexe) e_row e_column -> Paramètres récupérés (voir définition de l’évènement)

PAGE 17 / 92

Page 18: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

B.VII.2 Implémentation :

Une fois les fonctions définis, il convient alors de procéder à leur implémentation (juste en dessous de la définition) :

***************************************************************** LOCAL CLASSES: Implementation*****************************************************************===============================================================* class lcl_event_receiver (Implementation)**class lcl_event_receiver implementation.

method handle_toolbar.* § 2.In event handler method for event TOOLBAR: Append own functions* by using event parameter E_OBJECT. data: ls_toolbar type stb_button.*....................................................................* E_OBJECT of event TOOLBAR is of type REF TO CL_ALV_EVENT_TOOLBAR_SET.* This class has got one attribute, namly MT_TOOLBAR, which* is a table of type TTB_BUTTON. One line of this table is* defined by the Structure STB_BUTTON (see data deklaration above).*

* A remark to the flag E_INTERACTIVE:* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~* 'e_interactive' is set, if this event is raised due to* the call of 'set_toolbar_interactive' by the user.* You can distinguish this way if the event was raised* by yourself or by ALV* (e.g. in method 'refresh_table_display').* An application of this feature is still unknown... :-)

* append a separator to normal toolbar clear ls_toolbar. move 3 to ls_toolbar-butn_type. append ls_toolbar to e_object->mt_toolbar.* append an icon to show post table

clear ls_toolbar. move 'POSTES' to ls_toolbar-function.* MOVE icon_employee TO ls_toolbar-icon. move icon_detail to ls_toolbar-icon. move ' Voir les postes'(111) to ls_toolbar-quickinfo. move ' Vue poste'(112) to ls_toolbar-text. move ' ' to ls_toolbar-disabled. append ls_toolbar to e_object->mt_toolbar. endmethod.*------------------------------------------------------------------- method handle_double_click. data: ls_poste like line of t_poste, ls_entete like line of t_entete, p_vbeln like vbrp-vbeln.

* § 4.The event DOUBLE_CLICK provides parameters for row and column* of the click. Use row parameter to select a line of the* corresponding internal table. if poste eq 'P'.* read selected row from internal table gt_sflight read table t_poste index e_row-index into ls_poste. p_vbeln = ls_poste-vbeln.

else.

PAGE 18 / 92

Page 19: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

* read selected row from internal table gt_sflight read table t_entete index e_row-index into ls_entete. p_vbeln = ls_entete-vbeln.

endif.

* On appel la transaction VF03 pour afficher la Facture. set parameter id 'VF' field p_vbeln. call transaction 'VF03' and skip first screen.

endmethod. "handle_double_click

*------------------------------------------------------------------- method handle_user_command.* § 3.In event handler method for event USER_COMMAND: Query your* function codes defined in step 2 and react accordingly.

data: lt_rows type lvc_t_row.

case e_ucomm. when 'POSTES'. call method grid1->get_selected_rows importing et_index_rows = lt_rows. call method cl_gui_cfw=>flush. if sy-subrc ne 0.* add your handling, for example call function 'POPUP_TO_INFORM' exporting titel = g_repid txt2 = sy-subrc txt1 = 'Error in Flush'(500). else. perform show_poste_table tables lt_rows. endif. when 'FACTURE'. leave to screen 0. endcase. endmethod. "handle_user_command*-----------------------------------------------------------------endclass.** lcl_event_receiver (Implementation)*===================================================================

B.VII.3 Utilisation :

Enfin, lorsque la classe définissant les évènements est définie et implémentée, alors il faut créer une instance de l’objet et connecter nos propres au composant ALV.

Data : event_receiver type ref to lcl_event_receiver,

* ->Create Object to receive events and link them to handler methods.* When the ALV Control raises the event for the specified instance* the corresponding method is automatically called.** Création de l’instance create object event_receiver.

* Connection des Méthodes aux évènements.

PAGE 19 / 92

Page 20: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

set handler event_receiver->handle_user_command for grid1. set handler event_receiver->handle_toolbar for grid1. set handler event_receiver->handle_double_click for grid1.

* § 4.Call method 'set_toolbar_interactive' to raise event TOOLBAR. call method grid2->set_toolbar_interactive.

La fonction se définit comme suit :

Set handler “nom de l’objet »  -> « nom de la fonction » for « objet ALV »

PAGE 20 / 92

Page 21: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

B.VIII La grille ou composant ALVLe composant ALV est celui qui permet l’affichage de la grille, c’est ce dernier qui utilisera l’ensemble des objets précédemment définis. Nous ne présenterons pas par la suite l’ensemble des fonctions et propriétés disponibles (voir annexe).

B.VIII.1 Définition :Le composant ALV est de type cl_gui_alv_grid, et se déclare ainsi :

Data grid1 type ref to cl_gui_alv_grid,

B.VIII.2 Création de l’objet :

L’étape suivante consiste à créer une instance de l’objet grid1.La fonction « Create objet » prend pour argument

Le nom de l’objet (le composant ALV précédemment déclaré) Et le nom du container devant réceptionner la grille

* create an instance of alv control******************************************** Composant alv grid1* Nom du container custom_container1******************************************* create object grid1 exporting i_parent = custom_container1.

B.VIII.3 La fonction set_table_for_first_display.

Une fois l’objet crée, il suffit alors d’appeler la fonction set_table_for_first_display.

PAGE 21 / 92

Page 22: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

Cette dernière utilise plusieurs paramètres:

CALL METHOD grid1->set_table_for_first_display

      EXPORTING            I_STRUCTURE_NAME      = < string of type DD02L-TABNAME>

            IS_VARIANT            = < structure of type DISVARIANT>

            I_SAVE                = < var. of type CHAR01>            I_DEFAULT             = < var. of type CHAR01>            IS_LAYOUT             = < structure of type LVC_S_LAYO>            IS_PRINT              = < structure of type LVC_S_PRNT>

            IT_SPECIAL_GROUPS     = < internal table of type LVC_T_SGRP>

            IT_TOOLBAR_EXCLUDING  = < internal table of type UI_FUNCTIONS>

      CHANGING

            IT_OUTTAB             = < internal table>             IT_FIELDCATALOG       = < internal table of type LVC_T_FCAT>

            IT_SORT               = < internal table of type LVC_T_SORT>            IT_FILTER             = < internal table of type LVC_T_FILT>

Exemple :

*** DEFINITION de la grille ALV appelée. call method grid1->set_table_for_first_display exporting is_layout = gs_layout is_variant = gs_variant "&see below i_save = x_save "&see below changing it_outtab = t_entete[] it_fieldcatalog = gt_field_cat_entete[] .

if sy-subrc ne 0.* add your handling, for example call function 'POPUP_TO_INFORM' exporting titel = g_repid txt2 = sy-subrc txt1 = 'The control could not be ATTACHED'(510). endif.

PAGE 22 / 92

Page 23: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

EXPORTINGType Nom du paramètre Désignation

CATALOGUE I_STRUCTURE_NAME Nom de la structure du catalogue si elle appartient au dictionnaire ex : SFLIGHT

VARIANTE

IS_VARIANT Nom de la varianteI_SAVE Autres paramètres propre à la gestion des

variantesI_DEFAULT Autes paramètres propre à la gestion des

variantesIT_SPECIAL_GROUPS      Permet de définir des groupes de colonnes

(voir annexe)

LAYOUT IS_LAYOUT Nom du layout

IMPRESSIONIS_PRINT Structure définissant les paramètres

d’impression de l’ALV.CHANGING

TABLE DONNEES IT_OUTTAB Nom de la table interne

CATALOGUE IT_FIELDCATALOG Nom du catalogue si spécifique

TRIIT_SORT Table interne contenant les informations de

tri

FILTREIT_FILTER Table interne contenant les

informations de filtres.

IS_PRINT reçoit une structure de type LVC_S_PRN

Champs Type Désignation

PRINT CHAR Contrôle ALV : édition par impression

RESERVELNS INT4 Contrôle ALV : nbre de lignes réservées pour END_OF_PAGE

GRPCHGEDIT CHAR Ctrl ALV : format changement grpe définissable par utilis.

PRNTLSTINF CHAR Contrôle ALV : ne pas activer les informations de liste

PRNTSELINF CHAR Contrôle ALV : ne pas activer informations de sélection

PAGE 23 / 92

Page 24: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

IT_SORT Table interne de type internal table of type LVC_T_SORT.

Déclaration :

data: lt_sort_alv type lvc_t_sort with header line.CLEAR lt_sort_alv.

lt_sort_alv-spos = 1. lt_sort_alv-fieldname = 'SESSNO'. lt_sort_alv-up = 'X'. append lt_sort_alv.

Champs Type Désignation

SPOS NUMC 2 Séquence de tri

FIELDNAME CHAR 30 Contrôle ALV : nom de zone de table interne

UP CHAR 1 Code à 1 caractère

DOWN CHAR 1 Code à 1 caractère

GROUP CHAR 2 Chgmt gpe : insérer chgmt page et traits soulignement

SUBTOT CHAR 1 Editer total intermédiaire

COMP CHAR 1 Code à 1 caractère

EXPA CHAR 1 Code à 1 caractère

SELTEXT CHAR 40 Critère de tri

OBLIGATORY CHAR 1 Code à 1 caractère

LEVEL INT4 10 Nombre naturel

NO_OUT CHAR 1 Code à 1 caractère

PAGE 24 / 92

Page 25: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

IT_FILTER Table  interne de type LVC_T_FILT

Champs Type Désignation

FIELDNAME CHAR 30 Cntrl ALV : nom table de référence pour zone table interne

TABNAME CHAR 30 Cntrl ALV : nom table de référence pour zone table interne

REF_FIELD CHAR 30 Ctrl ALV : nom zone de référence pour zone table interne

REF_TABLE CHAR 30 Cntrl ALV : nom table de référence pour zone table interne

C_FIELD CHAR 30 Contrôle ALV : nom de zone de table interne

C_TAB CHAR 30 Nom de table LVC

C_VALUE CHAR 5 Table R/2

FLG_CQ CHAR 1 Code à 1 caractère

SELTEXT CHAR 40 Contrôle ALV : identificateur de colonne pour fct. dialogue

VALUF CHAR 80 Texte de longueur 80

VALUT CHAR 80 Texte de longueur 80

LOW CHAR 80 Texte de longueur 80

HIGH CHAR 80 Texte de longueur 80

SIGN CHAR 1 Code à 1 caractère

OPTION CHAR 2 Composante du n° de version

SIGN_ICON CHAR 4 Domaine défini imprécisément,

STYPE CHAR 1 Code à 1 caractère

DD_OUTLEN NUMC 6 Contrôle ALV : longueur d'édition en nbre de caractères

DECIMAL NUMC 6 Nombre de décimales

PAGE 25 / 92

Page 26: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

INTLEN NUMC 6 Longueur interne en octets

CONVEXIT CHAR 5 Routine de conversion

EDIT_MASK CHAR 60 Contrôle ALV : EditMask pour édition

LOWERCASE CHAR 1 Minuscules autorisées/non autorisées

INTTYPE CHAR 1 Type données ABAP (C,D,N,...)

DATATYPE CHAR 4 Type de données dans dictionnaire ABAP

EXCEPTION CHAR 1 Code à 1 caractère

NO_SIGN CHAR 1 Contrôle ALV : occulter les signes +/- lors édition

OR CHAR 1 Code à 1 caractère

ORDER NUMC 2 Séquence

*** DEFINITION de la grille ALV appelée. call method grid1->set_table_for_first_display exporting is_layout = gs_layout is_variant = gs_variant "&see below i_save = x_save "&see below changing it_outtab = t_entete[] it_fieldcatalog = gt_field_cat_entete[] .

if sy-subrc ne 0.* add your handling, for example call function 'POPUP_TO_INFORM' exporting titel = g_repid txt2 = sy-subrc txt1 = 'The control could not be ATTACHED'(510). endif.

B.VIII.4 La fonction refresh_table_displayCette fonction permet de réinitialiser l’objet ALV.

call method grid1->refresh_table_display.

B.VIII.5 La fonction set_focusCette méthode permet de sélectionner l’objet actif dans l’écran, dans l’exemple qui suit on choisit grid1.

PAGE 26 / 92

Page 27: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

call method cl_gui_control=>set_focus exporting control = grid1.

if sy-subrc ne 0.* add your handling, for example call function 'POPUP_TO_INFORM' exporting titel = g_repid txt2 = sy-subrc txt1 = 'The control could not be in focus'(510). endif.

B.VIII.6 Exemple :

INCLUDE <icon>.TYPE-POOLS: SLIS.

DATA: ok_code LIKE sy-ucomm, g_repid LIKE sy-repid, gs_layout TYPE lvc_s_layo,* Nom du contenair principal cont_on_main TYPE scrfname VALUE 'BCALVC_TOOLBAR_D100_C1'

* Utilisation de Variantes. gs_variant TYPE disvariant, "for parameter IS_VARIANT x_save value 'A', grid1 TYPE REF TO cl_gui_alv_grid, custom_container1 TYPE REF TO cl_gui_custom_container, event_receiver TYPE REF TO lcl_event_receiver,* Definition des catalogues utilisés. GT_FIELD_CAT_ENTETE type LVC_T_FCAT with header line..........

IF custom_container1 is initial.

* Définition du catalogue***************************************************************** DATA: POS TYPE I VALUE 1. clear GT_field_cat_entete.

GT_field_cat_entete-COL_POS = POS. GT_field_cat_entete-FIELDNAME = 'KUNAG'. GT_field_cat_entete-tabname = 't_entete'. GT_field_cat_entete-ref_field = 'KUNAG'. GT_field_cat_entete-REF_TABLE = 'VBRK'. GT_field_cat_entete-KEY = 'X'.

append GT_field_cat_entete.

* Fin de la definition du catalogue.***************************************************************** CLEAR gs_variant.

* 'gs_variant' must at least contain the report-id to allow* saving a variant. g_repid = sy-repid.* § 2.At least field REPORT of this structure has to be filled! gs_variant-report = g_repid.

PAGE 27 / 92

Page 28: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

* create a custom container control for our ALV Control CREATE OBJECT custom_container1 EXPORTING container_name = cont_on_main EXCEPTIONS cntl_error = 1 cntl_system_error = 2 create_error = 3 lifetime_error = 4 lifetime_dynpro_dynpro_link = 5. IF sy-subrc ne 0.* add your handling, for example CALL FUNCTION 'POPUP_TO_INFORM' EXPORTING titel = g_repid txt2 = sy-subrc txt1 = 'The control could not be created'(510). ENDIF.

* create an instance of alv control CREATE OBJECT grid1 EXPORTING i_parent = custom_container1.** Set a titlebar for the grid control* gs_layout-grid_title = 'Listes des factures'(100).* allow to select multiple lines gs_layout-sel_mode = 'A'. gs_layout-CWIDTH_OPT = 'X'.

*** DEFINITION de la grille ALV appelée. CALL METHOD grid1->set_table_for_first_display EXPORTING is_layout = gs_layout is_variant = gs_variant "&see below i_save = x_save "&see below CHANGING it_outtab = t_entete[] IT_FIELDCATALOG = GT_FIELD_CAT_ENTETE[] .

IF sy-subrc ne 0.* add your handling, for example CALL FUNCTION 'POPUP_TO_INFORM' EXPORTING titel = g_repid txt2 = sy-subrc txt1 = 'The control could not be ATTACHED'(510). ENDIF.

* § 4.Call method 'set_toolbar_interactive' to raise event TOOLBAR. CALL METHOD grid1->set_toolbar_interactive.

ENDIF. "IF grid1 IS INITIAL

CALL METHOD cl_gui_control=>set_focus EXPORTING control = grid1. IF sy-subrc ne 0.* add your handling, for example CALL FUNCTION 'POPUP_TO_INFORM' EXPORTING titel = g_repid txt2 = sy-subrc txt1 = 'The control could not be in focus'(510). ENDIF.

PAGE 28 / 92

Page 29: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

ENDMODULE. " PBO_100 OUTPUT

B.IX Gestion avec plusieurs ALV.

Afin de pouvoir gérer des ALV avec différents niveaux, il est préférable d’utiliser plusieurs écran, générer à partir du screen painter et de créer dans chacun un CUSTOM CONTROLE.La création et l’affichage des objets ALV sont alors gérés au sein des PBO et PAI. (Voir exemple fournit à la fin)Il est aussi possible de d’utiliser d’autres containers, lesquelles permettent de gérer plusieurs composants ALV..

PAGE 29 / 92

Page 30: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

B.X REALISATION PRATIQUE : ExempleVoici un schéma global fournit par SAP reprenant l’ensemble des étapes et composants :

NOTA :Nous invitons le lecteur à consulter les programmes de la classe de développement SLIS.

B.X.1 MISE EN ŒUVRE

Création de l’écran et insertion de l’objet. Déclaration des différents éléments dans le programme : catalogue, layout, variante, container, classe

d’objet.. Définition et implémentation des classes locales : évènements et autres. Création du catalogue Définition du layout Définition des paramètres propres aux variantes. Instanciation du container. (création) Instanciation de la grille(création). Définition de la grille. (affichage, paramétrages…) Instanciation et rattachement de la classe évènements.

NOTA : l’instanciation correspond à la création de l’objet, à l’aide par exemple de la fonction « CREATE OBJET ».

B.X.2 EXEMPLESExemple de programme simple avec un seul ALV :

program bcalvc_variants_exe.*&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&* Purpose:* ~~~~~~~~* This example illustrates how a variant can be chosen before

PAGE 30 / 92

Page 31: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

* the generation of the list.** Relevant function modules are:* - LVC_VARIANT_DEFAULT_GET* -> Get the default variant* - LVC_VARIANT_EXISTENCE_CHECK* -> Test if a variant exist. Useful at event AT SELECTION-SCREEN* - LVC_VARIANT_F4* -> F4 help pops up to select a variant* - LVC_VARIANT_SELECT (not used in this example!)* -> select a variant by name*-----------------------------------------------------------------* To check program behavior* ~~~~~~~~~~~~~~~~~~~~~~~~~* Create your own variants using the variant menu of ALV Control.* Chose one as a default variant and return to the selection screen.*&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

data: ok_code like sy-ucomm, gt_sflight type table of sflight, g_repid like sy-repid, mycontainer type scrfname value 'BCALV_VARIANTS_0100_C1',* reference to custom container: neccessary to bind ALV Control custom_container type ref to cl_gui_custom_container, grid1 type ref to cl_gui_alv_grid.*.........................................................* 'x_save' contains a flag to control which kind of variants the user* can save (in this example it is set to 'A' for all variant types).** Variables of type DISVARIANT identify a variant.* When provided as parameter for 'set_grid_for_first_display',* it must contain at least the report-id.*data: x_save, "for parameter I_SAVE: modus for saving variants default, "has to be set if the chosen variant is a default variant x_variant type disvariant, g_exit type c. "is set if the user has aborted a variant popup

* The variables 'def_variant' and 'spec_variant' are set during* interactions on the selection screen.* 'gs_variant' finally holds the chosen variant.data: def_variant type disvariant, "default variant spec_variant type disvariant, "specific variant gs_variant type disvariant. "finally chosen variant

*DATA: got_default. "marks that the default variant has been loaded*...........................................................******************************************************* Define a selection screen* to choose an already saved variant******************************************************

selection-screen begin of block vari with frame title text-002.parameters: p_no_v radiobutton group exec default 'X', p_def_v radiobutton group exec, p_spec_v radiobutton group exec, p_vari like disvariant-variant.selection-screen end of block vari.

*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~initialization. g_repid = sy-repid. x_save = 'A'. "The user may save all types of variants

PAGE 31 / 92

Page 32: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~at selection-screen output.* The default variant is fetched the first time the PBO of the* selection screen is called.* If a default variant exist, its identification* is saved in 'def_variant'.*if default = ' '. clear def_variant. move g_repid to def_variant-report. call function 'LVC_VARIANT_DEFAULT_GET' exporting i_save = x_save changing cs_variant = def_variant exceptions not_found = 2. if sy-subrc = 2. p_no_v = 'X'. p_def_v = ' '. p_spec_v = ' '. perform deactivate_def_v. exit. else.* set name of variant on selection screen p_vari = def_variant-variant. default = 'X'. endif.endif. "default IS INITIAL*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~at selection-screen on value-request for p_vari.* popup F4 help to select a variant

clear x_variant. move g_repid to x_variant-report.

call function 'LVC_VARIANT_F4' exporting is_variant = x_variant i_save = x_save importing e_exit = g_exit es_variant = spec_variant exceptions not_found = 1 others = 2. if sy-subrc ne 0. message id sy-msgid type sy-msgty number sy-msgno with sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. else. if g_exit ne 'X'.* set name of variant on selection screen p_vari = spec_variant-variant. endif. endif.*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~at selection-screen.* test if specified variant exist if p_spec_v = 'X'. clear spec_variant. move p_vari to spec_variant-variant. move g_repid to spec_variant-report.

PAGE 32 / 92

Page 33: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

call function 'LVC_VARIANT_EXISTENCE_CHECK' exporting i_save = x_save changing cs_variant = spec_variant exceptions wrong_input = 1 not_found = 2 program_error = 3 others = 4. 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.

*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~start-of-selection. select * from sflight into table gt_sflight.*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~end-of-selection.* set gs_variant according to the selection made clear gs_variant.

* execute without variant if p_no_v = 'X'. gs_variant-report = g_repid.

* execute with default variant elseif p_def_v = 'X'. move-corresponding def_variant to gs_variant.

* execute with specified variant elseif p_spec_v = 'X'. move-corresponding spec_variant to gs_variant.

else. call function 'POPUP_TO_INFORM' exporting titel = g_repid txt2 = space txt1 = 'Fatal error: No radio button active!'(550). leave program. endif.

call screen 100.

*---------------------------------------------------------------------** MODULE PBO OUTPUT **---------------------------------------------------------------------*module pbo output. set pf-status 'MAIN100'. if custom_container is initial.* create a custom container control for our ALV Control create object custom_container exporting container_name = mycontainer exceptions cntl_error = 1 cntl_system_error = 2 create_error = 3

PAGE 33 / 92

Page 34: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

lifetime_error = 4 lifetime_dynpro_dynpro_link = 5. if sy-subrc ne 0.* add your handling, for example call function 'POPUP_TO_INFORM' exporting titel = g_repid txt2 = sy-subrc txt1 = 'The control could not be created'(510). endif.

create object grid1 exporting i_parent = custom_container.

call method grid1->set_table_for_first_display exporting i_structure_name = 'SFLIGHT'* gs_variant-report must not be initial! is_variant = gs_variant i_save = x_save changing it_outtab = gt_sflight. endif.

endmodule.*---------------------------------------------------------------------** MODULE PAI INPUT **---------------------------------------------------------------------*module pai input. case ok_code. when 'EXIT'. perform exit_program.

endcase. clear ok_code.endmodule.*---------------------------------------------------------------------** FORM EXIT_PROGRAM **---------------------------------------------------------------------*form exit_program. call method custom_container->free. leave to screen 0.endform.*&---------------------------------------------------------------------**& Form DEACTIVATE_DEF_V*&---------------------------------------------------------------------** text*----------------------------------------------------------------------** --> p1 text* <-- p2 text*----------------------------------------------------------------------*form deactivate_def_v.* deactivate radio button for default variant loop at screen. if screen-name = 'P_DEF_V'. screen-input = 0. modify screen. endif. endloop.

endform. " DEACTIVATE_DEF_V

Exemple de programme avec deux ALV :LE programme qui suit est présenté juste comme illustration, la majeure partie du code non relatif à l’implémentation de l’ALV a été supprimée.

PAGE 34 / 92

Page 35: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

report zrsd0007 message-id zs no standard page heading line-size 132 line-count 65.***ALV***include <icon>.type-pools: slis.

*----------------------------------------------------------------------** TABLES **----------------------------------------------------------------------*

tables : kna1, " Base clients (partie générale)

.

.

.*----------------------------------------------------------------------** TABLES INTERNES **----------------------------------------------------------------------*

** Tables contenants tous les entetes (vbrk)types : begin of ty_entete ,zzhiez(10) type c ,kunag like vbrk-kunag,name1 like kna1-name1,vbeln like vbrk-vbeln,fkart like vbrk-fkart,konda like vbrk-konda,netwr like vbrk-netwr,fkdat like vbrk-fkdat,buchk like vbuk-buchk,zztext(20) type c,zztext5(30) type c,vkorg like vbrk-vkorg,vtweg like vbrk-vtweg,spart like vbrk-spart,end of ty_entete.

* Definition de structure

data : st_entete type ty_entete , st_poste type ty_poste .

**************** ENTETEdata : begin of t_entete occurs 0. include structure st_entete.data : end of t_entete.***************

********ALV

* Predefine a local class for event handling to allow the* declaration of a reference variable before the class is defined.class lcl_event_receiver definition deferred.**********

data: ok_code like sy-ucomm, g_repid like sy-repid, gs_layout type lvc_s_layo,* Nom du contenair principal

PAGE 35 / 92

Page 36: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

cont_on_main type scrfname value 'BCALVC_TOOLBAR_D100_C1'*'ZZ_controle_100' ,* Nom du contenair secondaire cont_on_dialog type scrfname value 'BCALVC_TOOLBAR_D101_C1',* Definition des catalogues utilisés. gt_field_cat_entete type lvc_t_fcatwith header line,

gt_field_cat_poste type lvc_t_fcatwith header line,

* Utilisation de Variantes. gs_variant type disvariant, "for parameter IS_VARIANT x_save value 'A', grid1 type ref to cl_gui_alv_grid, grid2 type ref to cl_gui_alv_grid, custom_container1 type ref to cl_gui_custom_container, custom_container2 type ref to cl_gui_custom_container, event_receiver type ref to lcl_event_receiver, event_receiver2 type ref to lcl_event_receiver.

***************************************************************** LOCAL CLASSES: Definition*****************************************************************===============================================================* class lcl_event_receiver: local class to* define and handle own functions.** Definition:* ~~~~~~~~~~~class lcl_event_receiver definition.

public section.

methods: handle_toolbar for event toolbar of cl_gui_alv_grid importing e_object e_interactive ,

handle_user_command for event user_command of cl_gui_alv_grid importing e_ucomm,

handle_double_click for event double_click of cl_gui_alv_grid importing e_row e_column.

private section.

endclass.** lcl_event_receiver (Definition)*===============================================================

***************************************************************** LOCAL CLASSES: Implementation*****************************************************************===============================================================* class lcl_event_receiver (Implementation)**

PAGE 36 / 92

Page 37: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

class lcl_event_receiver implementation.

method handle_toolbar.* § 2.In event handler method for event TOOLBAR: Append own functions* by using event parameter E_OBJECT. data: ls_toolbar type stb_button.*....................................................................* E_OBJECT of event TOOLBAR is of type REF TO CL_ALV_EVENT_TOOLBAR_SET.* This class has got one attribute, namly MT_TOOLBAR, which* is a table of type TTB_BUTTON. One line of this table is* defined by the Structure STB_BUTTON (see data deklaration above).*

* A remark to the flag E_INTERACTIVE:* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~* 'e_interactive' is set, if this event is raised due to* the call of 'set_toolbar_interactive' by the user.* You can distinguish this way if the event was raised* by yourself or by ALV* (e.g. in method 'refresh_table_display').* An application of this feature is still unknown... :-)

* append a separator to normal toolbar clear ls_toolbar. move 3 to ls_toolbar-butn_type. append ls_toolbar to e_object->mt_toolbar.* append an icon to show post table clear ls_toolbar. move 'POSTES' to ls_toolbar-function.* MOVE icon_employee TO ls_toolbar-icon. move icon_detail to ls_toolbar-icon. move ' Voir les postes'(111) to ls_toolbar-quickinfo. move ' Vue poste'(112) to ls_toolbar-text. move ' ' to ls_toolbar-disabled. append ls_toolbar to e_object->mt_toolbar. endmethod.*------------------------------------------------------------------- method handle_double_click. data: ls_poste like line of t_poste, ls_entete like line of t_entete, p_vbeln like vbrp-vbeln.

* § 4.The event DOUBLE_CLICK provides parameters for row and column* of the click. Use row parameter to select a line of the* corresponding internal table.* read selected row from internal table t_entete

read table t_entete index e_row-index into ls_entete. p_vbeln = ls_entete-vbeln.

* On appel la transaction VF03 pour afficher la Facture. set parameter id 'VF' field p_vbeln. call transaction 'VF03' and skip first screen.

endmethod. "handle_double_click

*------------------------------------------------------------------- method handle_user_command.* § 3.In event handler method for event USER_COMMAND: Query your* function codes defined in step 2 and react accordingly.

data: lt_rows type lvc_t_row.

PAGE 37 / 92

Page 38: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

case e_ucomm. when 'POSTES'. call method grid1->get_selected_rows importing et_index_rows = lt_rows. call method cl_gui_cfw=>flush. if sy-subrc ne 0.* add your handling, for example call function 'POPUP_TO_INFORM' exporting titel = g_repid txt2 = sy-subrc txt1 = 'Error in Flush'(500). else. perform show_poste_table tables lt_rows. endif. when 'FACTURE'. leave to screen 0. endcase. endmethod. "handle_user_command*-----------------------------------------------------------------endclass.** lcl_event_receiver (Implementation)*===================================================================

*----------------------------------------------------------------------** ECRAN DE SELECTION **----------------------------------------------------------------------*

*----------------------------------------------------------------------** INITIALIZATION **----------------------------------------------------------------------*

*----------------------------------------------------------------------** AT SELECTION-SCREEN **----------------------------------------------------------------------*

*----------------------------------------------------------------------** START OF SELECTION **----------------------------------------------------------------------*

start-of-selection.

** Controle sur les sélections faites** Recupération des données perform f_facture.end-of-selection.

*---------------------------------------------------------------------** CREATION ALV **---------------------------------------------------------------------* perform init_catalogue. call screen '100'.

********************************************************** f_facture* t_entete********************************************************

form f_facture .

PAGE 38 / 92

Page 39: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

endform.

**&---------------------------------------------------------------------***& Form select_table_poste**&---------------------------------------------------------------------*** text**----------------------------------------------------------------------*** -->P_LS_entete text**----------------------------------------------------------------------*form select_table_poste using p_ls_entete like line of t_entete .

endform.***********************************************************************

*---------------------------------------------------------------------** FORM EXIT_PROGRAM **---------------------------------------------------------------------*form exit_program.* The instance grid2 is freed not until the program exits from the* main screen.* (It is created only once during the first selection of SBOOK,* no matter how many times the second window is called).* call method custom_container1->free. if not custom_container2 is initial. call method custom_container2->free. endif. call method cl_gui_cfw=>flush. if sy-subrc ne 0.* add your handling, for example call function 'POPUP_TO_INFORM' exporting titel = g_repid txt2 = sy-subrc txt1 = 'Error in Flush'(500). endif. leave program.endform.

*&---------------------------------------------------------------------**& Module PBO_100 OUTPUT*&---------------------------------------------------------------------** text*----------------------------------------------------------------------*module pbo_100 output.

set pf-status 'MAIN100'.

if custom_container1 is initial. clear gs_variant.

* 'gs_variant' must at least contain the report-id to allow* saving a variant. g_repid = sy-repid.* § 2.At least field REPORT of this structure has to be filled! gs_variant-report = g_repid. gs_variant-handle = '0100'.* create a custom container control for our ALV Control create object custom_container1 exporting container_name = cont_on_main

PAGE 39 / 92

Page 40: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

exceptions cntl_error = 1 cntl_system_error = 2 create_error = 3 lifetime_error = 4 lifetime_dynpro_dynpro_link = 5. if sy-subrc ne 0.* add your handling, for example call function 'POPUP_TO_INFORM' exporting titel = g_repid txt2 = sy-subrc txt1 = 'The control could not be created'(510). endif.

* create an instance of alv control create object grid1 exporting i_parent = custom_container1.** Set a titlebar for the grid control* gs_layout-grid_title = 'Listes des factures'(100).* allow to select multiple lines gs_layout-sel_mode = 'A'. gs_layout-cwidth_opt = 'X'.

*** DEFINITION de la grille ALV appelée. call method grid1->set_table_for_first_display exporting is_layout = gs_layout is_variant = gs_variant "&see below i_save = x_save "&see below changing it_outtab = t_entete[] it_fieldcatalog = gt_field_cat_entete[] .

if sy-subrc ne 0.* add your handling, for example call function 'POPUP_TO_INFORM' exporting titel = g_repid txt2 = sy-subrc txt1 = 'The control could not be ATTACHED'(510). endif.

***********************************************************************

********* ->Create Object to receive events and link them to handler methods.* When the ALV Control raises the event for the specified instance* the corresponding method is automatically called.* create object event_receiver. set handler event_receiver->handle_user_command for grid1. set handler event_receiver->handle_toolbar for grid1. set handler event_receiver->handle_double_click for grid1.

*********

* § 4.Call method 'set_toolbar_interactive' to raise event TOOLBAR. call method grid1->set_toolbar_interactive.

endif. "IF grid1 IS INITIAL

PAGE 40 / 92

Page 41: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

call method cl_gui_control=>set_focus exporting control = grid1. if sy-subrc ne 0.* add your handling, for example call function 'POPUP_TO_INFORM' exporting titel = g_repid txt2 = sy-subrc txt1 = 'The control could not be in focus'(510). endif.

endmodule. " PBO_100 OUTPUT*&---------------------------------------------------------------------**& Module PAI_100 INPUT*&---------------------------------------------------------------------** text*----------------------------------------------------------------------*module pai_100 input.

case ok_code. when 'EXIT'. perform exit_program.

endcase. clear ok_code.endmodule. " PAI_100 INPUT

*&---------------------------------------------------------------------**& Module PBO_0101 OUTPUT*&---------------------------------------------------------------------** text*----------------------------------------------------------------------*module pbo_0101 output.

set pf-status 'MAIN101'.

if custom_container2 is initial.

* 'gs_variant' must at least contain the report-id to allow* saving a variant. g_repid = sy-repid.* § 2.At least field REPORT of this structure has to be filled! gs_variant-report = g_repid. gs_variant-handle = '0101'.* (the data from sbook is already selected)

* create a custom container control for our ALV Control create object custom_container2 exporting container_name = cont_on_dialog exceptions cntl_error = 1 cntl_system_error = 2 create_error = 3 lifetime_error = 4 lifetime_dynpro_dynpro_link = 5. if sy-subrc ne 0.* add your handling, for example call function 'POPUP_TO_INFORM' exporting titel = g_repid txt2 = sy-subrc txt1 = 'The control could not be created'(510). endif.* create an instance of alv control create object grid2 exporting i_parent = custom_container2.

PAGE 41 / 92

Page 42: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

** change title* gs_layout-grid_title = 'Liste des postes'(101). gs_layout-cwidth_opt = 'X'. gs_layout-sel_mode = ' '.

call method grid2->set_table_for_first_display exporting is_layout = gs_layout is_variant = gs_variant "&see below i_save = x_save "&see below changing it_outtab = t_poste[] it_fieldcatalog = gt_field_cat_poste[].

************DEFINITION****

********* ->Create Object to receive events and link them to handler methods.* When the ALV Control raises the event for the specified instance* the corresponding method is automatically called.* create object event_receiver2. set handler event_receiver2->handle_user_command for grid2. set handler event_receiver2->handle_double_click for grid2.

*********

* § 4.Call method 'set_toolbar_interactive' to raise event TOOLBAR. call method grid2->set_toolbar_interactive.

* Cas des autres appels else.*On efface. call method grid2->refresh_table_display.* On reaffiche. call method grid2->set_table_for_first_display exporting is_layout = gs_layout changing it_outtab = t_poste[] it_fieldcatalog = gt_field_cat_poste[].

endif. "IF custom_container2 IS INITIAL.***********************************************************************

call method cl_gui_control=>set_focus exporting control = grid2. if sy-subrc ne 0.* add your handling, for example call function 'POPUP_TO_INFORM' exporting titel = g_repid txt2 = sy-subrc txt1 = 'The control could not be in focus'(510). endif.

endmodule. " PBO_0101 OUTPUT

*&---------------------------------------------------------------------**& Module PAI_0101 INPUT*&---------------------------------------------------------------------** text*----------------------------------------------------------------------*module pai_0101 input. case ok_code.

PAGE 42 / 92

Page 43: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

when 'RETURN'. leave to screen 0. when 'FACTURE'. leave to screen 0. endcase. clear ok_code.endmodule. " PAI_0101 INPUT*&---------------------------------------------------------------------

*& Form show_poste_table*&---------------------------------------------------------------------

* text*----------------------------------------------------------------------

* -->P_ET_INDEX_ROWS text*----------------------------------------------------------------------

form show_poste_table tables p_et_index_rows structure lvc_s_row.

data: ls_selected_line like lvc_s_row, lf_row_index type lvc_index, ls_entete like line of t_entete.

clear t_poste[]. loop at p_et_index_rows into ls_selected_line. lf_row_index = ls_selected_line-index.* read selected row from internal table gt_sflight read table t_entete index lf_row_index into ls_entete.

* select corresponding lines of table sbook* and append new lines to global table perform select_table_poste using ls_entete.

endloop.

* call dialog screen and display new alv control data : n type i. describe table t_poste lines n. if n ne 0. call screen 101 . " STARTING AT 10 5. else. call function 'POPUP_TO_INFORM' exporting titel = g_repid txt1 = text-201 txt2 = text-200.

endif.endform. " show_booking_table

*---------------------------------------------------------------------** FORM init_catalogue **---------------------------------------------------------------------** ........ **---------------------------------------------------------------------*form init_catalogue.

data: pos type i value 1.* DATA: LS_FIELDCAT type LVC_S_FCAT.

* Définition du catalogue pour les entetes.* On affiche la hiérarchie que dans le cas ou on l'utilise.

PAGE 43 / 92

Page 44: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

clear gt_field_cat_entete.

gt_field_cat_entete-col_pos = pos. gt_field_cat_entete-fieldname = 'KUNAG'. gt_field_cat_entete-tabname = 't_entete'. gt_field_cat_entete-ref_field = 'KUNAG'. gt_field_cat_entete-ref_table = 'VBRK'. gt_field_cat_entete-key = 'X'.

append gt_field_cat_entete.

clear gt_field_cat_entete.

pos = pos + 1.

gt_field_cat_entete-col_pos = pos. gt_field_cat_entete-fieldname = 'ZZTEXT5'. gt_field_cat_entete-tabname = 't_entete'. gt_field_cat_entete-inttype = 'C'. gt_field_cat_entete-outputlen = '30'. gt_field_cat_entete-coltext = 'Motif de non comptabilisation'. gt_field_cat_entete-seltext = 'Motif de non comptabilisation'.

append gt_field_cat_entete. clear gt_field_cat_entete. pos = pos + 1.

gt_field_cat_poste-col_pos = pos. gt_field_cat_poste-fieldname = 'Z_FKIMG'. gt_field_cat_poste-tabname = 't_poste'. gt_field_cat_poste-coltext = 'QTE en UR'. gt_field_cat_poste-seltext = 'Quantité facturé en unité de référence'. gt_field_cat_poste-datatype = 'QUAN'. append gt_field_cat_poste. clear gt_field_cat_poste.

endform.

PAGE 44 / 92

Page 45: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

C Utilisation des fonctions ALV définies pas SAP

C.I Fonction Standart SAP pour une ALV rapide

Sap met à la disposition du développeur un ensemble de fonction permettant l’affichage d’un ALV de façon très rapide. Ces fonctions sont très pratiques mais ne couvrent pas l’étendue des possibilités offertes par une implémentations manuelles des composants ALV.

NOTE : D’autres fonctions existe et peuvent être trouvé au sein du groupe de fonction SLIS (Transaction SE80)

C.I.1 Affichage d’un ALV simple

C.I.1.A APPEL DE BASE DE LA FONCTION REUSE_ALV_LIST_DISPLAY call function 'REUSE_ALV_LIST_DISPLAY' exporting i_callback_program = g_repid it_fieldcat = gt_fieldcat[] i_save = x_save is_variant = gs_variant tables t_outtab = t_charge.

C.I.1.B DÉFINITION DE LA FONCTION

function reuse_alv_list_display.*" IMPORTING*" VALUE(I_INTERFACE_CHECK) DEFAULT SPACE*" VALUE(I_CALLBACK_PROGRAM) LIKE SY-REPID DEFAULT SPACE*" VALUE(I_CALLBACK_PF_STATUS_SET) TYPE SLIS_FORMNAME DEFAULT*" SPACE*" VALUE(I_CALLBACK_USER_COMMAND) TYPE SLIS_FORMNAME DEFAULT SPACE*" VALUE(I_STRUCTURE_NAME) LIKE DD02L-TABNAME OPTIONAL*" VALUE(IS_LAYOUT) TYPE SLIS_LAYOUT_ALV OPTIONAL*" VALUE(IT_FIELDCAT) TYPE SLIS_T_FIELDCAT_ALV OPTIONAL*" VALUE(IT_EXCLUDING) TYPE SLIS_T_EXTAB OPTIONAL*" VALUE(IT_SPECIAL_GROUPS) TYPE SLIS_T_SP_GROUP_ALV OPTIONAL*" VALUE(IT_SORT) TYPE SLIS_T_SORTINFO_ALV OPTIONAL

PAGE 45 / 92

Page 46: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

*" VALUE(IT_FILTER) TYPE SLIS_T_FILTER_ALV OPTIONAL*" VALUE(IS_SEL_HIDE) TYPE SLIS_SEL_HIDE_ALV OPTIONAL*" VALUE(I_DEFAULT) DEFAULT 'X'*" VALUE(I_SAVE) DEFAULT SPACE*" VALUE(IS_VARIANT) LIKE DISVARIANT STRUCTURE DISVARIANT DEFAULT*" SPACE*" VALUE(IT_EVENTS) TYPE SLIS_T_EVENT OPTIONAL*" VALUE(IT_EVENT_EXIT) TYPE SLIS_T_EVENT_EXIT OPTIONAL*" VALUE(IS_PRINT) TYPE SLIS_PRINT_ALV OPTIONAL*" VALUE(IS_REPREP_ID) TYPE SLIS_REPREP_ID OPTIONAL*" VALUE(I_SCREEN_START_COLUMN) DEFAULT 0*" VALUE(I_SCREEN_START_LINE) DEFAULT 0*" VALUE(I_SCREEN_END_COLUMN) DEFAULT 0*" VALUE(I_SCREEN_END_LINE) DEFAULT 0*" VALUE(I_BUFFER_ACTIVE) OPTIONAL*" EXPORTING*" VALUE(E_EXIT_CAUSED_BY_CALLER)*" VALUE(ES_EXIT_CAUSED_BY_USER) TYPE SLIS_EXIT_BY_USER*" TABLES*" T_OUTTAB*" EXCEPTIONS*" PROGRAM_ERROR

PAGE 46 / 92

Page 47: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

C.II Liste hiérarchique

C.II.1 Introduction : L’affichage de liste hiérarchique est une opération qui peut s’avérer utile pour certains reports, en effet l’affichage est alors beaucoup plus malléable et permet une meilleur gestion de l’information. Afin d’afficher correctement les informations il est indispensable de comprendre la méthode de gestion entre les entêtes et les items.

C.II.2 Clé de correpondanceAfin de pouvoir afficher les informations correctement on utilise une structure permettant de mettre en relation jusqu’à 6 clés deux tables.

Data gs_keyinfo type slis_keyinfo_alv.L’exemple suivant fait le lien entre la table des entêtes définis par les compagnies aérienes (SPFLI) et la table des vols (SCARR) :

* define keyinfo clear gs_keyinfo. gs_keyinfo-header01 = 'CARRID'. gs_keyinfo-item01 = 'CARRID'. gs_keyinfo-header02 = space. gs_keyinfo-item02 = 'CONNID'.

C.II.3 LayoutLe layout est la structure par laquelle on définit les propriétés graphiques de l’affichage.

Data gs_layout type slis_layout_alv.

PAGE 47 / 92

Page 48: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

C.II.3.A GESTION DE L’EXPANSION

exemple :

* e05_ls_layout-expand_all = 'X'.

* Nom du champ dans la table des entêtes* ce champs contient soit X soit space. e05_ls_layout-expand_fieldname = 'EXPAND'.

C.II.3.B GESTION DES LEDSouvent utilisé dans SAP les leds sont de bon indicateurs visuels, leur utilisation est elle-même très simple

* définit le champ utilisé e05_ls_layout-lights_fieldname = ‘light’

* Nom de la table interne auquels est ratachée la led e05_ls_layout-lights_tabname = g_tabname_item.

* Je ne sais pas e05_ls_layout-lights_condense = p_lightc.

C.II.3.C GESTION DES CHECKBOX* Nom du champ dans la table interne. e05_ls_layout-box_fieldname = ‘BOX’ .

* Table interne e05_ls_layout-box_tabname = g_tabname_header.

C.II.3.D AFFICHAGE DU DÉTAIL * Detailed screen e05_ls_layout-detail_popup= ‘X’. "   show detail in popup e05_ls_layout-detail_initial_lines = ‘X’ . " show also initial lines e05_ls_layout-detail_titlebar = ‘TEST’. " Titlebar for detail

PAGE 48 / 92

Page 49: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

C.II.3.E AUTRES POSSIBILITÉSKey_hotspot permet de modifier la forme du curseur lorsque celui-ci est présent sur une clé.Zebra change la couleur d’une ligne à l ‘autre.

PAGE 49 / 92

Page 50: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

C.III Liste sous forme de grilleLe programme BCALV_FULLSCREEN_DEMO

Cette fonction permet d’afficher une liste sous la forme d’une grille ALV.

CALL FUNCTION 'REUSE_ALV_GRID_DISPLAY' EXPORTING I_BACKGROUND_ID = 'ALV_BACKGROUND' "QBJ50 I_CALLBACK_PROGRAM = G_REPID I_STRUCTURE_NAME = 'SFLIGHT' IS_LAYOUT = GS_LAYOUT I_SAVE = G_SAVE IS_VARIANT = GS_VARIANT IT_EVENTS = GT_EVENTS[]* I_SCREEN_START_COLUMN = 0 "Use coordinates for* I_SCREEN_START_LINE = 0 "display as dialog box* I_SCREEN_END_COLUMN = 0* I_SCREEN_END_LINE = 0 IMPORTING E_EXIT_CAUSED_BY_CALLER = G_EXIT_CAUSED_BY_CALLER ES_EXIT_CAUSED_BY_USER = GS_EXIT_CAUSED_BY_USER TABLES T_OUTTAB = GT_OUTTAB EXCEPTIONS PROGRAM_ERROR = 1 OTHERS = 2.

PAGE 50 / 92

Page 51: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

C.IV Le catalogue

C.IV.1 Définition du catalogueLe catalogue est basé sur une table de type SLIS_T_FIELDCAT_ALV.

C.IV.2 Déclaration :data: ls_fieldcat type slis_fieldcat_alv.

Le tableau ci-dessous reprend la liste des champs disponible dans la structure SLIS_T_FIELDCAT_ALVCes derniers sont relativement similaires de ceux utilisés avec les composants ALV.On peut alors soit implémenter le catalogue de façon manuelle, ou utiliser des fonctions spécifiques :

call function 'REUSE_ALV_FIELDCATALOG_MERGE' exporting* Table interne contenant les champs i_internal_tabname = g_tabname_header* Nom de la structure i_structure_name = 'SCARR' changing* Table contenant le catalogue ct_fieldcat = e01_lt_fieldcat[].

Nom du champ Définition Désignationrow_pos like sy-curow output in rowcol_pos like sy-cucol position of the columnfieldname type slis_fieldnametabname type slis_tabnameref_fieldname like dd03p-fieldnameref_tabname like dd03p-tabnamecurrency(5) type ccfieldname type slis_fieldname Field with currency unitctabname type slis_tabname and tablequantity(3) type cqfieldname type slis_fieldname Field with quantity unitqtabname type slis_tabname and tableroundfieldname type slis_fieldnameroundtabname type slis_tabnameround type i Round in write statementdecimalsfieldname type slis_fieldnamedecimalstabname type slis_tabnamedecimals_out(6) type c " decimals in write statementtext_fieldname type slis_fieldnameexponent(3) type c exponent for floatskey(1) type c column with key-coloricon(1) type c As iconSymbol(1) type c As symbolcheckbox(1) type c As checkboxjust(1) type c (R)ight (L)eft (C)ent.lzero(1) type c leading zerono_sign(1) type c Write no-signno_zero(1) type c Write no-zeroedit_mask type slis_edit_mask

PAGE 51 / 92

Page 52: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

emphasize(4) type c Emphasizefix_column(1) type c Spalte fixierendo_sum(1) type c sum upno_out(1) type c (O)blig.(X)no outtech(1) type c technical fieldoutputlen like dd03p-outputlenOffset type dd03p-intlen Offsetseltext_l like dd03p-scrtext_l long key wordseltext_m like dd03p-scrtext_m middle key wordseltext_s like dd03p-scrtext_s Short key wordreptext_ddic like dd03p-reptext heading (ddic)ddictxt(1) type c (S)hort (M)iddle (L)ongrollname like dd03p-rollnamedatatype like dd03p-datatypeinttype like dd03p-inttypeddic_outputlen like dd03p-outputlenIntlen like dd03p-intlenlowercase like dd03p-lowercasekey_sel(1) type c Field not obligatoryno_sum(1) type c Do not sum upsp_group(4) type c Group specificationReprep(1) type c selection for rep/repinput(1) type c Inputhotspot(1) type c Hotspot

C.IV.3 Zone en entréeIl est possible de définir au sein de l’affichage de l’ALV des zones accessibles en écriture de façon très simple, en effet il suffit de mettre la valeur ‘X’ dans le champs input du catalogue. Lorsqu’une zone est modifiée, la table interne est alors automatiquement mise à jour.

C.IV.4 EXAMPLE d’implémentation manuelle

data: gt_fieldcat type slis_t_fieldcat_alv. perform fieldcat_init using gt_fieldcat[]....

form fieldcat_init using rt_fieldcat type slis_t_fieldcat_alv. data: ls_fieldcat type slis_fieldcat_alv. data: pos type i value 1.

clear ls_fieldcat. ls_fieldcat-col_pos = pos. ls_fieldcat-fieldname = 'VBELN'. ls_fieldcat-ref_fieldname = 'VBELN'. ls_fieldcat-ref_tabname = 'VBAK'. ls_fieldcat-key = 'X'. append ls_fieldcat to rt_fieldcat. clear ls_fieldcat.

PAGE 52 / 92

Page 53: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

pos = pos + 1. ls_fieldcat-col_pos = pos. ls_fieldcat-fieldname = 'KUNNR'. ls_fieldcat-ref_fieldname = 'KUNNR'. ls_fieldcat-ref_tabname = 'VBAK'. ls_fieldcat-key = 'X'. append ls_fieldcat to rt_fieldcat. clear ls_fieldcat. pos = pos + 1. ls_fieldcat-col_pos = pos. ls_fieldcat-fieldname = 'NAME1'. ls_fieldcat-ref_fieldname = 'NAME1'. ls_fieldcat-ref_tabname = 'KNA1'.* LS_FIELDCAT-KEY = 'X'. append ls_fieldcat to rt_fieldcat. clear ls_fieldcat. pos = pos + 1. ls_fieldcat-col_pos = pos. ls_fieldcat-fieldname = 'POSNR'. ls_fieldcat-ref_fieldname = 'POSNR'. ls_fieldcat-ref_tabname = 'VBAP'.* LS_FIELDCAT-KEY = 'X'. append ls_fieldcat to rt_fieldcat.

clear ls_fieldcat. pos = pos + 1. ls_fieldcat-col_pos = pos. ls_fieldcat-fieldname = 'KWERT'. ls_fieldcat-ref_fieldname = 'KWERT'. ls_fieldcat-ref_tabname = 'KONV'. ls_fieldcat-cfieldname = 'WAERK'.

* LS_FIELDCAT-KEY = 'X'. append ls_fieldcat to rt_fieldcat. clear ls_fieldcat. pos = pos + 1. ls_fieldcat-col_pos = pos. ls_fieldcat-fieldname = 'WAERK'. ls_fieldcat-ref_fieldname = 'WAERK'. ls_fieldcat-ref_tabname = 'VBAK'.* LS_FIELDCAT-KEY = 'X'. append ls_fieldcat to rt_fieldcat.Endform.

PAGE 53 / 92

Page 54: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

C.V Gestion du menu et de la barre des boutonsLe menu utilisateur est définit à l’aide de la transaction SE41, on peut retrouver ci-dessous un exemple de fonctions standards implémentées.Il est important de définir manuellement chacune des options.

Ensuite, il faut alors définir au sein du programme le menu utilisateur choisit avant l’appel de la fonction ALV. set pf-status 'STANDARD001'.

Enfin, il suffit alors de renseigner le paramètre adéquate de la fonction, à savoir I_CALLBACK_PF_STATUS_SET = 'PF_STATUS_SET'

La valeur du texte (‘PF_STATUS_SET’) ne semble pas avoir de réelle valeur.Dans le cas ou aucun menu ne serait fournit alors c’est le menu par défaut qui est repris :

C.V.1.A GESTION DES CODES TRANSACTIONS ET CLIK DE LA SOURIS.

La zone F2CODE dans la structure du layout permet d’associer une transaction au double click.Ainsi si on souhaite utiliser la notion de détail suite au double click sur une ligne, on utilisera le code ‘&ETA’.Si le champ F2CODE n’est pas renseigné alors le code fonction généré suite à un double click est : ‘&IC1’.

Par contre si le développeur souhaite utiliser plusieurs code fonction spécifique au sein de son programme, il lui suffit d’affecter le nom d’un sous programme au niveau du paramètre ‘I_CALLBACK_USER_COMMAND’si le code fonction est spécifique alors la fonction est automatiquement appelée.

PAGE 54 / 92

Page 55: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

form fcode_bearbeiten using if_fcode like sy-ucomm cs_selfield type slis_selfield. * if _code contient le code de la transaction* cs_selfield contient toutes les informations relatives à la selection faites :

data: l_ta(4) type c value 'TCH1'.

case if_fcode. when 'WAHL'. "menubutton read table gt_outtab index cs_selfield-tabindex. "cursorposit. set parameter id 'CAR' field gt_outtab-carrid. set parameter id 'CON' field gt_outtab-connid. call transaction l_ta and skip first screen. "# EC* clear r_ucomm. when '&IC1'. "dobbleclick read table gt_outtab into gt_outtab index rs_selfield-tabindex. set parameter id 'CAR' field gt_outtab-carrid. set parameter id 'CON' field gt_outtab-connid. call transaction l_ta and skip first screen. "# EC* clear r_ucomm. endcase.

endform

Exemple issu d’un déboguage de la transaction VL10D sur la fonction FCODE_BEARBEITEN.

TABNAME C 30 CT_ITEM TABINDEX I 4 1SUMINDEX I 4 0 ENDSUM C 1SEL_TAB_FIELD C 60 CT_ITEM-MATNR VALUE C 60 65 BEFORE_ACTION C 1AFTER_ACTION C 1REFRESH C 1IGNORE_MULTI C 1COL_STABLE C 1 ROW_STABLE C 1 EXIT C 1 FIELDNAME C 30 MATNR GROUPLEVEL I 4 0COLLECT_FROM I 40COLLECT_TO I 4 0

PAGE 55 / 92

Page 56: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

C.VI Gestion des variantes

C.VI.1 Définition

* Déclarationdata : gs_variant type disvariant, "for parameter IS_VARIANT

g_save value 'A'.

C.VI.2 Implémentation

* Implémentationclear gs_variant.

* 'gs_variant' must at least contain the report-id to allow* saving a variant.

data: g_repid like sy-repid.

g_repid = sy-repid.

* § 2.At least field REPORT of this structure has to be filled!

gs_variant-report = g_repid.

C.VI.3 Fonction utiles

C.VI.3.A GESTION DU F4Afin de gérer le ‘F4’ dans un selection-screen, on peut utiliser la fonction suivante :REUSE_ELV_VARIANT_F4.

call function 'REUSE_ALV_VARIANT_F4' exporting is_variant = g_variant i_save = g_save i_tabname_header = g_tabname_header i_tabname_item = g_tabname_item* it_default_fieldcat = importing e_exit = g_exit es_variant = gx_variant exceptions not_found = 2.

C.VI.3.B SAUVEGARDE DE LA VARIANTE DANS LE PAI (A VÉRIFIER)On peut utiliser la fonction REUSE_ALV_VARIANT_EXISTENCE

if not p_vari is initial. move g_variant to gx_variant. move p_vari to gx_variant-variant. call function 'REUSE_ALV_VARIANT_EXISTENCE' exporting i_save = g_save changing cs_variant = gx_variant. g_variant = gx_variant. else. perform variant_init. endif.

PAGE 56 / 92

Page 57: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

C.VI.3.C RÉCUPÉRATION DE LA VARIANTE PAR DÉFAUTPour la récupération de la variante par défaut on peut utiliser la fonction :REUSE_ALV_VARIANT_DEFAULT_GET.

call function 'REUSE_ALV_VARIANT_DEFAULT_GET' exporting i_save = g_save changing cs_variant = gx_variant exceptions not_found = 2.

PAGE 57 / 92

Page 58: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

C.VII Table contenant les donnéesLa table contenant les données doit être une table interne. Voici un exemple de définition d’une table affichée par la suite :

*- table de chargementdata : begin of t_charge occurs 0, vbeln like vbak-vbeln " n° cde, kunnr like vbak-kunnr " donneur d'ordre, name1 like kna1-name1 " nom, posnr like vbap-posnr " n° poste, matnr like vbap-matnr " code article, arktx like vbap-arktx " désignation article, kschl like zsd02-kschl " type condition, vtext like zsd02-vtext " libellé, kwert like konv-kwert " valeur condition, waerk like vbak-waerk " devise, z_kbetr(11) type p decimals 2 " montant, koein like konv-waers " valeur = devise ou %, kpein like konv-kpein " unité de prix, kmein like konv-kmein " unité qtité, erdat like vbak-erdat " date cde, ernam like vbak-ernam " auteur de la saisie, end of t_charge.

PAGE 58 / 92

Page 59: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

C.VIII Les événements La structure utilisé est la suivante :

Data gt_events type slis_t_event.

Les évènements disponibles doivent être définit dans une table interne du type ci-dessus. La table interne contient alors 2 champs, le premier correspond à l’événement disponible alors que le second correspond à la fonction associée. Name nom de l’évènement Form Nom de la fonction associé

On peut utiliser la fonction suivanteREUSE_ALV_EVENT_GET afin de récupérer l’ensemble des fonctions disponibles dans une table interne.

call function 'REUSE_ALV_EVENTS_GET' exporting i_list_type = 0 importing et_events = e03_lt_events.

Il est alors très simple d’associer une fonciton à au moins un des évènements disponibles.(La gestion du click passe par l’utilisation du f2code).

Liste des évènements :

CALLER_EXIT USER_COMMAND TOP_OF_PAGE TOP_OF_COVERPAGE END_OF_COVERPAGE FOREIGN_TOP_OF_PAGE FOREIGN_END_OF_PAGE PF_STATUS_SET LIST_MODIFY TOP_OF_LIST END_OF_PAGE END_OF_LIST AFTER_LINE_OUTPUT BEFORE_LINE_OUTPUT REPREP_SEL_MODIFY SUBTOTAL_TEXT

PAGE 59 / 92

Page 60: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

Définition des constantes utilisées dans le type-spool SLIS :

* Eventsslis_ev_item_data_expand type slis_formname value 'ITEM_DATA_EXPAND',slis_ev_reprep_sel_modify type slis_formname value 'REPREP_SEL_MODIFY',slis_ev_caller_exit_at_start type slis_formname value 'CALLER_EXIT',slis_ev_user_command type slis_formname value 'USER_COMMAND',slis_ev_top_of_page type slis_formname value 'TOP_OF_PAGE',slis_ev_top_of_coverpage type slis_formname value 'TOP_OF_COVERPAGE',slis_ev_end_of_coverpage type slis_formname value 'END_OF_COVERPAGE',slis_ev_foreign_top_of_page type slis_formname value 'FOREIGN_TOP_OF_PAGE',slis_ev_foreign_end_of_page type slis_formname value 'FOREIGN_END_OF_PAGE',slis_ev_pf_status_set type slis_formname value 'PF_STATUS_SET',slis_ev_list_modify type slis_formname value 'LIST_MODIFY',slis_ev_top_of_list type slis_formname value 'TOP_OF_LIST',slis_ev_end_of_page type slis_formname value 'END_OF_PAGE',slis_ev_end_of_list type slis_formname value 'END_OF_LIST',slis_ev_after_line_output type slis_formname value 'AFTER_LINE_OUTPUT',slis_ev_before_line_output type slis_formname value 'BEFORE_LINE_OUTPUT',slis_ev_subtotal_text type slis_formname value 'SUBTOTAL_TEXT'.

read table e03_lt_events with key name = slis_ev_top_of_page into ls_event. if sy-subrc = 0. move gc_formname_top_of_page to ls_event-form. append ls_event to e03_lt_events. endif.

PAGE 60 / 92

Page 61: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

C.IX Commentaires : Entête de pageOn peut utiliser la fonction REUSE_ALV_COMMENTARY_WRITE.La table utilisée afin de stocké les informations est de type : slis_t_listheader

typ(1) type c, " H = Header, S = Selection, A = Action key(20) type c, info type slis_entry,exemple de sortie générée à l’écran :

constants:gc_formname_top_of_page type slis_formname value 'TOP_OF_PAGE'.

data: gt_list_top_of_page type slis_t_listheader.

perform e04_comment_build using gt_list_top_of_page[].

call function 'REUSE_ALV_COMMENTARY_WRITE' exporting it_list_commentary = gt_list_top_of_page.

form e04_comment_build using e04_lt_top_of_page type slis_t_listheader. data: ls_line type slis_listheader.** Listenüberschrift: Typ H clear ls_line. ls_line-typ = 'H'.* LS_LINE-KEY: not used for this type ls_line-info = ‘intitulé de liste’. append ls_line to e04_lt_top_of_page.* Kopfinfo: Typ S clear ls_line. ls_line-typ = 'S'. ls_line-key = ‘Clé 1’. ls_line-info = ‘Texte d information’. append ls_line to e04_lt_top_of_page. ls_line-key = ‘Clé 2’. append ls_line to e04_lt_top_of_page.* Aktionsinfo: Typ A clear ls_line. ls_line-typ = 'A'.* LS_LINE-KEY: not used for this type ls_line-info = ‘Statut liste’. append ls_line to e04_lt_top_of_page.endform.

PAGE 61 / 92

Page 62: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

C.X Gestion de plusieurs ALV sur un seul écran (programme BALVBT01)

La gestion de plusieurs ALV sur un seul écran est possible à l’aide des fonctions standards sans avoir recours à un container spécifique.Nous nous efforcerons de présenter les fonctions permettant cette souplesse :

Exemple d’écran généré :

C.X.1 InitialisationLa première fonction a appellé a pour objectif d’intialiser les blocs :

Data repid like sy-repid.Repid = sy-repid.

call function 'REUSE_ALV_BLOCK_LIST_INIT' exporting

* nom du programme i_callback_program = repid

* Nom de la fonction appelée traité les commandes utilisateurs. i_callback_user_command = 'USER_COMMAND'

* Définit que le menu est propre à l’utilisateur i_callback_pf_status_set = ‘PF_STATUS_SET’* IT_EXCLUDING = .

Le menu utilisateur sera à définir dans le programme, voir autre section.

PAGE 62 / 92

Page 63: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

C.X.2 Définition des blocs

Il est alors possible d’afficher autant de blocs que l’on souhaite soit de type classique ou hiérarchique.On utilise alors les fonctions suivantes :

Ces fonctions sont relativement proche des fonctions classique auquelles elles font référence, le développeur est donc invité à s’y reporter.

C.X.2.A ALV CLASSIQUE :

call function 'REUSE_ALV_BLOCK_LIST_APPEND' exporting

* CATALOGUE it_fieldcat = xfield* LAYOUT is_layout = x_layout

* TABLE INTERNE i_tabname = 'XDATA'

*EVENEMENT it_events = gt_xevents

i_text = ‘first block’

tables t_outtab = xdata.

C.X.2.B ALV HIÉRARCHIQUE :

call function 'REUSE_ALV_BLOCK_LIST_HS_APPEND' exporting is_layout = h_layout it_fieldcat = hfield is_keyinfo = gs_keyinfo i_header_tabname = 'HDATA' i_item_tabname = 'IDATA' it_events = gt_hevents i_text = text-0b2 tables t_outtab_header = hdata t_outtab_item = idata.

C.X.3 Affichage des blocsEnfin, afin de pouvoir afficher tout les blocs à l’écran il suffit alors d’appeler la fonction suivante :

PAGE 63 / 92

Page 64: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

CALL FUNCTION 'REUSE_ALV_BLOCK_LIST_DISPLAY'* EXPORTING* I_INTERFACE_CHECK = ' '* IS_PRINT =* I_SCREEN_START_COLUMN = 0* I_SCREEN_START_LINE = 0* I_SCREEN_END_COLUMN = 0* I_SCREEN_END_LINE = 0* IMPORTING* E_EXIT_CAUSED_BY_CALLER =* ES_EXIT_CAUSED_BY_USER =* EXCEPTIONS* PROGRAM_ERROR = 1* OTHERS = 2.

PAGE 64 / 92

Page 65: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

C.X.4 Gestion des extraits – sauvegarde de table interne(Programme BALVEX01)

La gestion des extraits consiste à sauvegarder des informations contenus dans une table interne. Cette fonctionnalité offerte par SAP est particulièrement intéressante. Une fois enregistrée les informations sont alors consultables dans le temps même si les données de bases ont été modifiées.

C.X.4.A INITIALISATIONIl est conseillé de placer cette fonction le plus tôt possible, cela est particulièrement important si on souhaite gérer la notion d’aide sur un écran de sélection.Dans notre exemple nous l’avons placé au sein de l’initialisation.

data: gs_extract1 like disextract.data: gs_extract2 like disextract.*---------------------------------------------------------------------**initialization.

call function 'REUSE_ALV_EXTRACT_AT_INIT' changing cs_extract1 = gs_extract1 cs_extract2 = gs_extract2.

La fonction se contente de retourner des informations sur l’environnement en cours.

function reuse_alv_extract_at_init.*"----------------------------------------------------------------------*"*"Lokale Schnittstelle:*" IMPORTING*" VALUE(I_REPORT) LIKE SY-REPID OPTIONAL*" VALUE(I_HANDLE) LIKE DISEXTRACT-HANDLE OPTIONAL*" VALUE(I_LOG_GROUP) LIKE DISEXTRACT-LOG_GROUP OPTIONAL*" VALUE(I_USERNAME) LIKE DISEXTRACT-USERNAME OPTIONAL*" CHANGING*" VALUE(CS_EXTRACT1) LIKE DISEXTRACT*" STRUCTURE DISEXTRACT*" VALUE(CS_EXTRACT2) LIKE DISEXTRACT*" STRUCTURE DISEXTRACT*"----------------------------------------------------------------------

C.X.4.BLa fonction suivante permet de mettre à jour les structures GS_EXTRACT1 et 2.GS_EXTRACT1 correspond à la structure pour l’enregistrement des données.GS_EXTRACT2 correspond à la structure pour le chargement des données.

P_SAVE et P_LOAD définissent le mode (SAVE or LOAD)P_EX1 et P_EX2 correspondent aux nom des extraitsC_P_EX1 et C_P_EX2 sont les textes de désignation.CS_EXTRACT1 et CS_EXTRACT2 sont les structures reprenant toutes les informations.

AT SELECTION-SCREEN.

CALL FUNCTION 'REUSE_ALV_EXTRACT_AT_SELSCREEN' EXPORTING I_P_SAVE = P_SAVE I_P_LOAD = P_LOAD CHANGING C_P_EX1 = P_EX1 C_P_EX2 = P_EX2 C_P_EXT1 = P_EXT1 C_P_EXT2 = P_EXT2

PAGE 65 / 92

Page 66: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

CS_EXTRACT1 = GS_EXTRACT1 CS_EXTRACT2 = GS_EXTRACT2.

C.X.4.C AIDE F4On utilise pour cela les fonctions suivantes, la première concerne le champs pour l’enregistrement d’extrait alors que la seconde concerne le chargement.Ces fonctions peuvent être placées au sein de

call function 'REUSE_ALV_EXTRACT_AT_F4_P_EX1'* EXPORTING* I_PARNAME_P_EXT1 = 'P_EXT1' changing c_p_ex1 = p_ex1 c_p_ext1 = p_ext1 cs_extract1 = gs_extract1.

call function 'REUSE_ALV_EXTRACT_AT_F4_P_EX2'* EXPORTING* I_PARNAME_P_EXT2 = 'P_EXT2' changing c_p_ex2 = p_ex2 c_p_ext2 = p_ext2 cs_extract2 = gs_extract2.

C.X.4.D ENREGISTREMENT DE L’EXTRAIT

call function 'REUSE_ALV_EXTRACT_SAVE' exporting is_extract = gs_extract1 i_get_selinfos = 'X' tables it_exp01 = gt_sflight.

C.X.4.E CHARGEMENT DE L’EXTRAIT

call function 'REUSE_ALV_EXTRACT_LOAD' exporting is_extract = gs_extract2 tables et_exp01 = gt_sflight.

C.X.4.F EXEMPLE

REPORT BALVEX01 NO STANDARD PAGE HEADING.* DB-TableTABLES SFLIGHT.* Type-pool of ALVTYPE-POOLS: SLIS.

* Report SelectionsSELECT-OPTIONS CARRID FOR SFLIGHT-CARRID.SELECT-OPTIONS CONNID FOR SFLIGHT-CONNID.SELECT-OPTIONS FLDATE FOR SFLIGHT-FLDATE.SELECTION-SCREEN SKIP 1.

selection-screen begin of block extract with frame title text-ext.* selection-screen begin of line. parameters: p_noex radiobutton group extr. selection-screen comment 3(50) text-ex1 for field p_noex. selection-screen end of line.

selection-screen begin of line. parameters: p_save radiobutton group extr.

PAGE 66 / 92

Page 67: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

selection-screen comment 3(50) text-ex3 for field p_save. selection-screen end of line.

selection-screen begin of line. selection-screen comment 3(29) text-ex2 for field p_ex1. parameters: p_ex1 like ltex-exname. selection-screen end of line. selection-screen begin of line. selection-screen comment 3(29) text-ex5 for field p_ext1. parameters: p_ext1 like ltex-text. selection-screen end of line.

selection-screen begin of line. parameters: p_load radiobutton group extr. selection-screen comment 3(50) text-ex4 for field p_load. selection-screen end of line.

selection-screen begin of line. selection-screen comment 3(29) text-ex2 for field p_ex2. parameters: p_ex2 like ltex-exname. selection-screen comment 47(40) p_ext2 for field p_ex2. selection-screen end of line.selection-screen end of block extract.

* Data to be displayedDATA: GT_SFLIGHT LIKE SFLIGHT OCCURS 0.DATA: GS_EXTRACT1 LIKE DISEXTRACT.DATA: GS_EXTRACT2 LIKE DISEXTRACT.*---------------------------------------------------------------------**INITIALIZATION.

CALL FUNCTION 'REUSE_ALV_EXTRACT_AT_INIT' CHANGING CS_EXTRACT1 = GS_EXTRACT1 CS_EXTRACT2 = GS_EXTRACT2.

AT SELECTION-SCREEN.

CALL FUNCTION 'REUSE_ALV_EXTRACT_AT_SELSCREEN' EXPORTING I_P_SAVE = P_SAVE I_P_LOAD = P_LOAD CHANGING C_P_EX1 = P_EX1 C_P_EX2 = P_EX2 C_P_EXT1 = P_EXT1 C_P_EXT2 = P_EXT2 CS_EXTRACT1 = GS_EXTRACT1 CS_EXTRACT2 = GS_EXTRACT2.

break-point.

* Process on value requestAT SELECTION-SCREEN ON VALUE-REQUEST FOR P_EX1.

CALL FUNCTION 'REUSE_ALV_EXTRACT_AT_F4_P_EX1'* EXPORTING* I_PARNAME_P_EXT1 = 'P_EXT1' CHANGING C_P_EX1 = P_EX1 C_P_EXT1 = P_EXT1 CS_EXTRACT1 = GS_EXTRACT1.

AT SELECTION-SCREEN ON VALUE-REQUEST FOR P_EX2.

CALL FUNCTION 'REUSE_ALV_EXTRACT_AT_F4_P_EX2'* EXPORTING* I_PARNAME_P_EXT2 = 'P_EXT2' CHANGING C_P_EX2 = P_EX2 C_P_EXT2 = P_EXT2

PAGE 67 / 92

Page 68: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

CS_EXTRACT2 = GS_EXTRACT2.

START-OF-SELECTION.* Selection IF P_LOAD IS INITIAL. SELECT * FROM SFLIGHT INTO TABLE GT_SFLIGHT WHERE CARRID IN CARRID AND CONNID IN CONNID AND FLDATE IN FLDATE. ENDIF.

IF P_SAVE = 'X'. CALL FUNCTION 'REUSE_ALV_EXTRACT_SAVE' EXPORTING IS_EXTRACT = GS_EXTRACT1 I_GET_SELINFOS = 'X' TABLES IT_EXP01 = GT_SFLIGHT.* EXIT. ENDIF.

IF P_LOAD = 'X'. CALL FUNCTION 'REUSE_ALV_EXTRACT_LOAD' EXPORTING IS_EXTRACT = GS_EXTRACT2 TABLES ET_EXP01 = GT_SFLIGHT.

ENDIF.

* Call ABAP/4 List Viewer CALL FUNCTION 'REUSE_ALV_LIST_DISPLAY' EXPORTING I_CALLBACK_PROGRAM = GS_EXTRACT1-REPORT I_STRUCTURE_NAME = 'SFLIGHT' I_SAVE = 'A' TABLES T_OUTTAB = GT_SFLIGHT.

PAGE 68 / 92

Page 69: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

D ANNEXES :

PAGE 69 / 92

Page 70: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

D.I Utilisation de classe sous SAP.NOTA : Cette partie est donnée à titre informatif et ne peut en aucuns cas se substituer à l’aide fournit par SAP :SAP Library

Basis components Abap Programming and Runtime Environment

BC-Abap ProgrammingAbap Objects

D.I.1 Déclaration d’une classe

Les classes sous SAP se décomposent en trois parties :

Public : accessible par tous Privé : accessible uniquement par les objets de la classe Protected : même attribut que pour la partie privée mais accessible aussi par les classes déclarées

« ami »

Chacune d’entre elle peut contenir des données des méthodes Des événements.

D.I.2 Exemple de définition de classe.

***************************************************************** LOCAL CLASSES: Definition*****************************************************************===============================================================

CLASS C_LIST DEFINITION.

  PUBLIC SECTION.

  METHODS: FCODE_HANDLER FOR EVENT BUTTON_CLICKED OF STATUS                              IMPORTING FCODE,           LIST_CHANGE   FOR EVENT SPEED_CHANGE OF I_VEHICLE                             IMPORTING NEW_SPEED,           LIST_OUTPUT.

  PRIVATE SECTION.

  DATA: ID TYPE I,        REF_SHIP  TYPE REF TO C_SHIP,        REF_TRUCK TYPE REF TO C_TRUCK,

        BEGIN OF LINE,          ID TYPE I,          FLAG,          IREF  TYPE REF TO I_VEHICLE,          SPEED TYPE I,        END OF LINE,        LIST LIKE SORTED TABLE OF LINE WITH UNIQUE KEY ID.

ENDCLASS.

PAGE 70 / 92

Page 71: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

D.I.3 Implémentation d’une classe

CLASS C_LIST IMPLEMENTATION.

  METHOD FCODE_HANDLER . *CODE

  ENDMETHOD.

  METHOD LIST_CHANGE . *CODE

  ENDMETHOD.

  METHOD LIST_OUTPUT.*CODE

  ENDMETHOD.

ENDCLASS.

PAGE 71 / 92

Page 72: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

E Annexe sur ALV standard

E.I Gestion des groupes de colonnes pour les variantes :La gestion de groupe de colonnes prédéfinies pour les variantes peut s’avérer des plus intéressante, la marche à suivre est aussi très simple.La première étape consiste à déclarer la table de type : LVC_T_SGRP.

DATA : t_groupe type LVC_T_SGRP.

Ensuite, il suffit d’affecter au champ SP_GROUP du catalogue une clé de 4 chiffres (digits) correspondant à un groupe.Enfin il suffit d’ajouter ces informations dans la table « t_groupe ».

CLEAR T_GROUPE.T_GROUPE-SP_GROUPE = ‘1001’.T_GROUPE-TEXT = ‘Groupe A’.APPEND T_GROUPE.

 

PAGE 72 / 92

Page 73: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

E.II Ajout d’un menu.

Il faut commencer par définir un statut associé au programme en utilisant la transaction SE41.Cette transaction permet d’affecter des codes transactions aux différents boutons, ainsi que de créer son menu. Les codes fonctions seront alors récupérés au sein de l’OK_CODE dans le PAI de l’écran (dans le cas d’un Ecran) ou dans la fonction AT SELECTION-SCREEN.

Enfin, au sein du programme on utilise l’instruction suivante, dans le PBO, pour insérer le menu :

* MAIN100 est le nom du statues SET PF-STATUS ‘MAIN100’

PAGE 73 / 92

Page 74: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

Création d’un ALV à l’aide d’une fonction standard SAP.

La première étape consiste à créer un catalogue.

Puis on fait appel à la fonction standard «'REUSE_ALV_LIST_DISPLAY” Exemple

* Global data declarationinclude vsd03top.

* Initialization fieldcataloginitialization. g_repid = sy-repid. perform fieldcat_init using gt_fieldcat[].

* Data selectionstart-of-selection. perform select_data tables gt_outtab.

* Display listend-of-selection.

******************************************************************************

call function 'REUSE_ALV_LIST_DISPLAY' exporting i_callback_program = g_repid it_fieldcat = gt_fieldcat[] tables t_outtab = gt_outtab.******************************************************************************

*-----------------------------------------------------------------------* Forms*-----------------------------------------------------------------------

* Initialization fieldcatalog

form fieldcat_init using rt_fieldcat type slis_t_fieldcat_alv. data: ls_fieldcat type slis_fieldcat_alv. data: pos type i value 1.

clear ls_fieldcat. ls_fieldcat-col_pos = pos. ls_fieldcat-fieldname = 'SCARR-CARRID'. ls_fieldcat-ref_fieldname = 'CARRID'. ls_fieldcat-ref_tabname = 'SCARR'. ls_fieldcat-key = 'X'. append ls_fieldcat to rt_fieldcat. clear ls_fieldcat. pos = pos + 1. ls_fieldcat-col_pos = pos. ls_fieldcat-fieldname = 'SCARR-CARRNAME'. ls_fieldcat-ref_fieldname = 'CARRNAME'. ls_fieldcat-ref_tabname = 'SCARR'. append ls_fieldcat to rt_fieldcat. clear ls_fieldcat. pos = pos + 1. ls_fieldcat-col_pos = pos. ls_fieldcat-fieldname = 'SPFLI-CONNID'. ls_fieldcat-ref_fieldname = 'CONNID'.

PAGE 74 / 92

Page 75: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

ls_fieldcat-ref_tabname = 'SPFLI'. append ls_fieldcat to rt_fieldcat. clear ls_fieldcat. pos = pos + 1. ls_fieldcat-col_pos = pos. ls_fieldcat-fieldname = 'SPFLI-CITYFROM'. ls_fieldcat-ref_fieldname = 'CITYFROM'. ls_fieldcat-ref_tabname = 'SPFLI'. append ls_fieldcat to rt_fieldcat. clear ls_fieldcat. pos = pos + 1. ls_fieldcat-col_pos = pos. ls_fieldcat-fieldname = 'SPFLI-AIRPFROM'. ls_fieldcat-ref_fieldname = 'AIRPFROM'. ls_fieldcat-ref_tabname = 'SPFLI'. ls_fieldcat-no_out = 'X'. append ls_fieldcat to rt_fieldcat. clear ls_fieldcat. pos = pos + 1. ls_fieldcat-col_pos = pos. ls_fieldcat-fieldname = 'SPFLI-CITYTO'. ls_fieldcat-ref_fieldname = 'CITYTO'. ls_fieldcat-ref_tabname = 'SPFLI'. append ls_fieldcat to rt_fieldcat. clear ls_fieldcat. pos = pos + 1. ls_fieldcat-col_pos = pos. ls_fieldcat-fieldname = 'SPFLI-AIRPTO'. ls_fieldcat-ref_fieldname = 'AIRPTO'. ls_fieldcat-ref_tabname = 'SPFLI'. ls_fieldcat-no_out = 'X'. append ls_fieldcat to rt_fieldcat. clear ls_fieldcat. pos = pos + 1. ls_fieldcat-col_pos = pos. ls_fieldcat-fieldname = 'SPFLI-DEPTIME'. ls_fieldcat-ref_fieldname = 'DEPTIME'. ls_fieldcat-ref_tabname = 'SPFLI'. append ls_fieldcat to rt_fieldcat. clear ls_fieldcat. pos = pos + 1. ls_fieldcat-col_pos = pos. ls_fieldcat-fieldname = 'SPFLI-ARRTIME'. ls_fieldcat-ref_fieldname = 'ARRTIME'. ls_fieldcat-ref_tabname = 'SPFLI'. append ls_fieldcat to rt_fieldcat. clear ls_fieldcat. pos = pos + 1. ls_fieldcat-col_pos = pos. ls_fieldcat-fieldname = 'SPFLI-DISTANCE'. ls_fieldcat-ref_fieldname = 'DISTANCE'. ls_fieldcat-ref_tabname = 'SPFLI'. ls_fieldcat-no_out = 'X'. append ls_fieldcat to rt_fieldcat. clear ls_fieldcat. pos = pos + 1. ls_fieldcat-col_pos = pos. ls_fieldcat-fieldname = 'SPFLI-DISTID'. ls_fieldcat-ref_fieldname = 'DISTID'. ls_fieldcat-ref_tabname = 'SPFLI'. ls_fieldcat-no_out = 'X'. append ls_fieldcat to rt_fieldcat.endform. "fieldcat_init

* Data selection

PAGE 75 / 92

Page 76: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

form select_data tables rt_outtab like gt_outtab[]. select distinct scarr~carrid scarr~carrname spfli~connid spfli~cityfrom spfli~airpfrom spfli~cityto spfli~airpto spfli~deptime spfli~arrtime spfli~distance spfli~distid into (rt_outtab-scarr-carrid, rt_outtab-scarr-carrname, rt_outtab-spfli-connid, rt_outtab-spfli-cityfrom, rt_outtab-spfli-airpfrom, rt_outtab-spfli-cityto, rt_outtab-spfli-airpto, rt_outtab-spfli-deptime, rt_outtab-spfli-arrtime, rt_outtab-spfli-distance, rt_outtab-spfli-distid) from scarr inner join spfli on scarr~carrid = spfli~carrid where scarr~carrid between 'AA' and 'LH'. append rt_outtab. endselect.endform. " select_data

PAGE 76 / 92

Page 77: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

E.III Output Options of Columns

Field name Comp. type Dtype(length) Value range

Use

CHECKBOX LVC_CHECKB CHAR(1) SPACE, 'X'

Outputting a checkbox. The checkbox cannot be modified by the user. Parameter sel_mode of the layout structure allows the user to select multiple rows in the grid control (see also: get_selected_rows).

COL_POS LVC_COLPOS INT4(10) natural number

Relevant only if the relative column positions should not be identical to the sequence of fields in the field catalog when the list is displayed for the first time.

The parameter determines the relative column position of the field for list output. The user can interactively modify the order of the columns. If this parameter is initial for each field catalog entry, the order of the columns corresponds to the sequence of fields in the field catalog.

DO_SUM LVC_DOSUM Char(1) SPACE, 'X'

If this field is set, the ALV uses this field to calculate the total (this corresponds to the generic totals function in the toolbar.)

EMPHASIZE LVC_EMPHSZ Char(4) SPACE, 'X' or 'Cxyz' (x:'1'-'9'; y,z: '0'=off '1'=on)

If the field is set to 'X', the ALV uses a pre-defined color for highlighting the column. If the character field begins with 'C' (color code), the remaining numbers have the following meaning:

x: color number

y: intensified display on/off

y: inverse display on/off

For more information on color coding, see the F1 help on the FORMAT statement.HOTSPOT LVC_HOTSPT Char(1) SPACE, 'X'

If this field is set, all cells of this column are hotspot-sensitive.KEY LVC_KEY Char(1) SPACE, 'X'

If this field is set, the ALV grid control color-codes the column as a key field and fixes this column during horizontal scrolling. The order of the key columns in the ALV grid control can be modified interactively. In contrast to the ABAP List Viewer, the ALV grid control allows you to directly hide key columns with NO_OUT (field KEY_SEL is not used).

LOWERCASE LOWERCASE Char(1) SPACE, 'X'If this field is set, the ALV grid control recognizes upper/lower case in the output table. This affects the sorting of fields, for example.

NO_OUT LVC_NOOUT Char(1) SPACE, 'X'If you set this field, you hide the relevant column in the list. Nevertheless, the column is available in the field selection and can be interactively selected by the user as a display field. The ALV displays the contents of hidden fields on the detail screen for a row in the grid control.

NO_SUM LVC_NOSIGN Char(1) SPACE, 'X'If you set this field, you lock totals calculation for the relevant field.

OUTPUTLEN LVC_OUTLEN Numc(6) 0 (default setting), nDetermines the column width of the field:

PAGE 77 / 92

Page 78: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

If the field has a reference to the Data Dictionary, you can leave the field set to its initial value. In this case, the ALV adopts the output length of the relevant domain.

For fields without reference to the DDIC, you must specify the desired field output length.

TECH LVC_TECH Char(1) SPACE, 'X'If this field is set, the relevant field is not displayed on the list and cannot be shown interactively. The field is only known in the field catalog. (For example, it must not be specified as a sorting criterion).

 

PAGE 78 / 92

Page 79: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

E.IV Formatting Column Contents 

Fields DECIMALS_O , EDIT_MASK , EXPONENT , NO_SIGN and ROUND correspond to WRITE additions DECIMALS , USING EDIT MASK , EXPONENT , NO-SIGN and ROUND . For information on combining these fields with fields CURRENCY and QUANTITY (for WRITE: UNIT ), see the F1 help for the WRITE edit option.

Field name Comp. type Dtype(length) Value range

Use

DECIMALS_O LVC_DECMLS Char(6) initial, natural number

Relevant only if no currency field is assigned to the field and if CURRENCY has a value. The value in this field determines the number of digits to be displayed after the comma.

DECMFIELD LVC_DFNAME Char(30) SPACE, field name of output table

Defining the digits after the comma on a row-by-row basis. You can use an additional field in the output table to determine how many digits are to be displayed after the comma in each row.

EDIT_MASK LVC_EDTMSK Char(60) SPACE, conv (conversion exit)

If you set a conversion exit (for example, conv = ' ==ALPHA ' for function module

CONVERSION_EXIT_ALPHA_OUTPUT ), you enforce output conversion for the

associated output field. (See also F1 help for WRITE edit option USING EDIT MASK) .

See also: Using the Conversion Exit

EXPONENT LVC_EXPONT Char(3) initial, integer

Determines a fixed exponent for the field. The field must be of internal type F. (See also F1 help for WRITE edit option EXPONENT ).

ICON LVC_ICON Char(1) SPACE, 'X'

If this field is set, the column contents of the output table are output as an icon. The column contents must consist of valid icon strings ( @xx@ or @xx\Q <Quickinfo> @ ).

You should consider the problem of printing icons.

JUST LVC_JUST Char(1) SPACE, 'R', 'L','C'

Relevant only to fields of data type CHAR or NUMC . Justifications:

'R': right justified

'L': left justified

'C': centered

How the column header is justified, depends on how the column contents are justified. You cannot justify the column header separately.

LZERO LVC_LZERO Char(1) SPACE, 'X'

PAGE 79 / 92

Page 80: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

Relevant only to fields of data type NUMC . In the default setting, the ALV control

displays these fields right justified without leading zeros. If you set LZERO , leading zeros are displayed.

NO_SIGN LVC_NOSIGN Char(1) SPACE, 'X'Relevant only to value fields. If you set NO-SIGN , values are displayed without signs (see also F1 help for the WRITE edit options).

NO_ZERO LVC_NOZERO Char(1) SPACE, 'X'If NO_ZERO is set, no zeros are displayed for initial value fields. The cell remains empty.

ROUND LVC_ROUND Char(10) initial, natural numberDisplaying a value of type P scaled by the power of ten. For positive ROUND values, the ALV grid control moves the comma to the left; otherwise, it moves the comma to the right.(See also F1 help for the WRITE edit options)

ROUNDFIELD LVC_RNDFN Char(30)  Defining scaled output on a row-by-row-basis. You can use an additional field in the output table to determine how the relevant field is scaled in each row.

SYMBOL LVC_SYMBOL Char(1) SPACE, 'X'If this field is set, the column contents are displayed as a symbol.The column contents of the internal table must consist of valid symbol signs. The caller should consider the problem of printing symbols. (It is usually possible to print symbols, but they may not be output correctly depending on the printer configuration).

PAGE 80 / 92

Page 81: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

E.V Properties of the Grid Control 

General display options

Field name Description Value range

CWIDTH_OPT If this field is set, the ALV grid control optimizes the column width. You can then see the column header and the contents of the cells of this column.

SPACE, 'X'

SMALLTITLE If this field is set, the title size in the grid control is set to the font size of the column header.

SPACE, 'X'

 

Grid customizing

Field name Description Value range

GRID_TITLE Title between grid control and toolbar Character string of 70 characters at most

NO_HEADERS If this field is set, column headers are hidden. SPACE, 'X'

NO_HGRIDLN If this field is set, columns are displayed without horizontal grid lines.

SPACE, 'X'

NO_MERGING If this field is set, cells are not merged when a column is sorted.

SPACE, 'X'

NO_ROWMARK If this field is set, the button at the beginning of a row is hidden in selection modes cell selection ( SEL_MODE = 'D' ) and column/row selection ( SEL_MODE = 'A' ).

SPACE, 'X'

NO_TOOLBAR If this field is set, the toolbar is hidden. SPACE, 'X'

NO_VGRIDLN If this field is set, columns are displayed without vertical grid lines.

SPACE, 'X'

SEL_MODE Set the selection mode (see table below). SPACE, 'A', 'B', 'C', 'D'

 

Selection modes for SEL_MODE

Value Mode Possible selections Comment

SPACE same as 'B' see 'B' Default setting

'A' Column and row selection

(see graphic)

Multiple columns

Multiple rows

The user selects the rows through pushbuttons at the left border of the grid control.

'B' Simple selection, list box

Multiple columns

Multiple rows

 

'C' Multiple selection, list box

Multiple  

PAGE 81 / 92

Page 82: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

columns

Multiple rows

'D' Cell selection Multiple columns

Multiple rows

Any cells

The user selects the rows through pushbuttons at the left border of the grid control.

 

ALV grid control with column and row selection

 

 

 

 

 

PAGE 82 / 92

Page 83: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

E.VI Events of Class CL_GUI_ALV_GRID 

The section Working With the ALV Grid Control describes the special points and issues you must consider when you handle events of the ALV grid control.

User-defined Text Output

Event Application

print_end_of_list Define output text to be printed at the end of the entire list

print_top_of_list Define output text to be printed at the beginning of the entire list

print_end_of_page Define output text to be printed at the end of each page

print_top_of_page Define output text to be printed at the beginning of each page

subtotal_text Define self-defined subtotals texts

 

Mouse-controlled Actions in the Grid Control

Event Application

double_click Query a double-click on a cell of the grid control

hotspot_click Query a hotspot click on columns defined for this purpose in advance

onDrag Collect information when elements of the ALV grid control are dragged

onDrop Process information when elements of the ALV grid control are dropped

onDropComplete Perform final actions after successful Drag&Drop

onDropGetFlavor Distinguish between options for Drag&Drop behavior

 

Processing of Self-defined and Standard Functions

Event Application

before_user_command Query self-defined and standard function codes

user_command Query self-defined function codes

after_user_command Query self-defined and standard function codes

 

Definition of Self-defined Functions

PAGE 83 / 92

Page 84: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

Event Application

toolbar Change, delete or add GUI elements in the toolbar

menu_button Define menus for menu buttons in the toolbar

context_menu_request Change context menu

PAGE 84 / 92

Page 85: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

E.VII Découpage de l’écran afin d’afficher plusieurs ALV.

E.VII.1 Définition de l’écran de sélectionAfin de pouvoir afficher plusieurs objets ALV au sein d’un même écran, on peut procéder selon deux méthodes :

Créer deux « CUSTOM CONTROL ». Utiliser un conténaire divisant en cellules le custom control originel. Chaque cellule est alors

identifiable par un numéro de ligne et de colonne.

Seule la seconde méthode est détaillé par la suite.

Processus :

1 On utilise toujours un objet de type « custom_container » rattaché au « cutom_control » de l’écran.

2 On créer alors un objet de type « splitter_custom » rattacher au « custom_container » définit précédemment.

3 On peut alors soit définir des conténaires et y attacher les objets ALV, soit rattacher directement les objets ALV(Le parent étant alors le splitter_continer)

Etape 1 : * Nom du custom control définit dans l’écran. data : cont_on_main type scrfname value 'ALV_1',

* Définition du conténaire principal rattaché au custom control  custom_container_parent type ref to cl_gui_custom_container,

* Définition du contenair divisé en cellule custom_splitter type ref to cl_gui_splitter_container,

* Définition des contenairs acceuillant les objets ALV.

PAGE 85 / 92

Page 86: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

custom_container1 type ref to cl_gui_container,* Définition des objets ALV. grid1 type ref to cl_gui_alv_grid, grid2 type ref to cl_gui_alv_grid.

Etape 2 :Cette partie du code peut être placé au sein du code PBO :

If custom_container_parent is initial.

* Création du contenair principal en relation avec le custom control* de l’écran. create object custom_container_parent exporting container_name = cont_on_main exceptions cntl_error = 1 cntl_system_error = 2 create_error = 3 lifetime_error = 4 lifetime_dynpro_dynpro_link = 5.

* Premier containercreate object custom_splitterexporting* Nombre de lignesrows = 1 * Nombre de colonescolumns = 2* Le parent est le contenair définit précedementparent = custom_container_parent.

* Permet de rendre la barre de separation mobile. call method custom_splitter->set_border exporting border = gfw_false.

* Méthode 1* Affectation du contenair 1 affecté à la grille 1. call method custom_splitter->get_container exporting row = 1 column = 1 receiving container = custom_container1.

* create an instance of alv control create object grid1 exporting i_parent = custom_container1.

* Méthode 2 create object grid2 exporting i_parent = custom_splitter.

call method custom_splitter->add_control exporting row = 1 column = 2 control = grid2

.

PAGE 86 / 92

Page 87: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

E.VIII Affichage d’un objet ALV sans utiliser de screen Painter Pour se faire on utilise un container particulier qui permet de définir sa taille et ses caractéristiques d’affichage.

* Déclaration

Data : dock_container type ref to cl_gui_docking_container.

Data: l_repid like sy-repid, l_dynnr like sy-dynnr.

* Affectation de valeur g_repid = sy-repid. l_dynnr = sy-dynnr.

* Ce code peut être mis dans un PBO.

*create docking container create object dock_container exporting repid = l_repid dynnr = l_dynnr

* Définit le placement du container (droite, gauche, bas , haut etc…) side = cl_gui_docking_container=>dock_at_left exceptions cntl_error = 1 cntl_system_error = 2 create_error = 3 lifetime_error = 4 lifetime_dynpro_dynpro_link = 5.

*set height and width call method dock_container->set_position exporting height = 150 width = 100 exceptions cntl_error = 1 cntl_system_error = 2.

Une fois que le contenair est crée, on peut alors soit l’utiliser pour afficher nos composant, soit utiliser une autre contenair tel que le splitter_container. Il suffit alors de définir le dock_container comme étant le « parent ».

Le placement du container par rapport à l’écran est définit par le paramètre SIDE NOTA : Ce container offre la possibilité de pouvoir redimensionner à l’aide de la souris le container.

Static Constant Type / Value Description / Usedock_at_left Type I Value 1 Left-hand edge of the screendock_at_top Type I Value 2 Top edge of the screendock_at_bottom Type I Value 4 Bottom edge of the screendock_at_right Type I Value 8 Right-hand edge of the screenproperty_docking Type I Value 470 Docking property

property_floating Type I Value 480 Floating property

PAGE 87 / 92

Page 88: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

E.IX Définir un menu contextuel : Bouton droit de la souris.

L’objet ALV permet de définir un menu appeler par le bouton droit de la souris ou (SHIFT + F10).

Le menu contextuel est automatiquement appelé sauf dans les cas suivants : SAP Picture Control SAP Toolbar Control

Où il faudra utiliser la fonction :

CALL METHOD picture->display_context_menu          exporting context_menu = context_menu          exceptions error = 1.

Parameter Meaning

context_menu Instance of the class CL_CTMENU for constructing and displaying a context menu ( see also: Context Menu).

Fonction définis relative au menu contextuel.Method Description

LOAD_GUI_STATUS Charge un menu défini dans le menu painter SE41constants: c_pname type program value 'CTMENU_BUILD', c_status_context type cua_status value 'CT_STATIC'.

call method cl_ctmenu=>load_gui_status exporting program = c_pname status = c_status_context

menu = p_menu.ADD_FUNCTION Adds a function :

CALL METHOD E_OBJECT->ADD_FUNCTION EXPORTING FCODE = 'AA' “code fonction TEXT = TEXT-150. "American Airlines

ADD_MENU Adds a menu that you defined in the Menu PainterADD_SUBMENU Adds a menu that you defined in the Menu Painter as a submenu

Data l_submenu type ref to cl_ctmenu.* Add new submenu create object l_submenu.* Add functions call method l_submenu->add_function exporting fcode = c_fcode1 text = text-001.* Add separator call method l_submenu->add_separator.* Add functions call method l_submenu->add_function exporting fcode = c_fcode3 text = text-003.* Dans la fonction handler p_menu = e_object call method p_menu->add_submenu exporting menu = l_submenu text = text-m01.

ADD_SEPARATOR Adds a separator call method p_menu->add_separator.

RESET Reset to initial valueHIDE FUNCTIONS Hides a function

DATA: LT_STD_FCODES TYPE UI_FUNCTIONS.

* Fonction standard ALV

PAGE 88 / 92

Page 89: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

APPEND CL_GUI_ALV_GRID=>MC_FC_DELETE_FILTER TO LT_STD_FCODES.

* Fonction perso.APPEND 'AA' TO LT_STD_FCODES.

CALL METHOD E_OBJECT->HIDE_FUNCTIONS EXPORTING FCODES = LT_STD_FCODES.

SHOW_FUNCTIONS Shows a functionDATA: LT_STD_FCODES TYPE UI_FUNCTIONS.* Fonction standard ALVAPPEND CL_GUI_ALV_GRID=>MC_FC_DELETE_FILTER TO LT_STD_FCODES.

* Fonction perso.APPEND 'AA' TO LT_STD_FCODES.

CALL METHOD E_OBJECT->SHOW_FUNCTIONS EXPORTING FCODES = LT_STD_FCODES.

DISABLE_FUNCTIONS Inactivates a functionENABLE_FUNCTIONS Activates a function

Tout comme pour les autres événements, on utilise une classe locale, celle-ci peut aussi contenir d’autres méthodes.

Définition :

INCLUDE <ICON>.

********** Predefine a local class for event handling to allow the* declaration of a reference variable before the class is defined.CLASS LCL_EVENT_RECEIVER DEFINITION DEFERRED.

DATA EVENT_RECEIVER TYPE REF TO LCL_EVENT_RECEIVER.

Définition de la classe***************************************************************** LOCAL CLASSES: Definition*****************************************************************===============================================================* class lcl_event_receiver: local class to* define and handle own functions.** Definition:* ~~~~~~~~~~~CLASS LCL_EVENT_RECEIVER DEFINITION.

PUBLIC SECTION.

METHODS : HANDLE_USER_COMMAND FOR EVENT USER_COMMAND OF CL_GUI_ALV_GRID IMPORTING E_UCOMM,

HANDLE_CONTEXT_MENU FOR EVENT CONTEXT_MENU_REQUEST OF CL_GUI_ALV_GRID IMPORTING E_OBJECT.

PRIVATE SECTION.* Les LT_STD_FCODES et LT_OWN_FCODES permettent de regrouper* par groupes les fonctions (Voir implémentation).

DATA: LT_STD_FCODES TYPE UI_FUNCTIONS, LT_OWN_FCODES TYPE UI_FUNCTIONS.

PAGE 89 / 92

Page 90: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

ENDCLASS.** lcl_event_receiver (Definition)*===============================================================

Implémentation : (Voir le programme BCALV_GRID_06)

***************************************************************** LOCAL CLASSES: Implementation*****************************************************************===============================================================* class lcl_event_receiver (Implementation)*CLASS LCL_EVENT_RECEIVER IMPLEMENTATION. METHOD HANDLE_USER_COMMAND.* § 5.Implement event handler method for event USER_COMMAND:* Query the function code defined in event handler method for* event CONTEXT_MENU_REQUEST.

DATA: LT_ROWS TYPE LVC_T_ROW.

CASE E_UCOMM.* handle user commands of context menu WHEN 'AA'. PERFORM SELECT_TABLE_SFLIGHT USING 'AA' CHANGING GT_SFLIGHT. CALL METHOD GRID1->REFRESH_TABLE_DISPLAY. WHEN 'LH'. PERFORM SELECT_TABLE_SFLIGHT USING 'LH' CHANGING GT_SFLIGHT. CALL METHOD GRID1->REFRESH_TABLE_DISPLAY. WHEN 'UA'. PERFORM SELECT_TABLE_SFLIGHT USING 'UA' CHANGING GT_SFLIGHT. CALL METHOD GRID1->REFRESH_TABLE_DISPLAY. ENDCASE. ENDMETHOD. "handle_user_command

*----------------------------------------------------------------** § 2.Use event handler method for event CONTEXT_MENU_REQUEST to define* your own context menu. METHOD HANDLE_CONTEXT_MENU.

constants: c_pname type program value 'CTMENU_BUILD', c_status_context type cua_status value 'CT_STATIC'. * Chargement d’un menu définit dans le menu paintercall method cl_ctmenu=>load_gui_status exporting program = c_pname status = c_status_context menu = p_menu.

* On ajoute les fonctions standards le groupe LT_STD_FCODES

APPEND CL_GUI_ALV_GRID=>MC_FC_COL_OPTIMIZE TO LT_STD_FCODES. APPEND CL_GUI_ALV_GRID=>MC_FC_HELP TO LT_STD_FCODES. APPEND CL_GUI_ALV_GRID=>MC_FC_COL_INVISIBLE TO LT_STD_FCODES. APPEND CL_GUI_ALV_GRID=>MC_FC_DELETE_FILTER TO LT_STD_FCODES.

* On ajoute nos propres fonctions au groupe LT_OWN_FCODES. APPEND 'AA' TO LT_OWN_FCODES. APPEND 'LH' TO LT_OWN_FCODES.

PAGE 90 / 92

Page 91: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

APPEND 'UA' TO LT_OWN_FCODES.

* On ajoute nos lignes de menus et les codes fonctions associés.* Celle-ci seront récupérées dans le E_UCOMM dans l’événement user_command

CALL METHOD E_OBJECT->ADD_FUNCTION EXPORTING* Code récupéré dans le E_UCOMM

FCODE = 'AA' TEXT = TEXT-150. "American Airlines CALL METHOD E_OBJECT->ADD_FUNCTION EXPORTING FCODE = 'LH' TEXT = TEXT-151. "Lufthansa CALL METHOD E_OBJECT->ADD_FUNCTION EXPORTING FCODE = 'UA' TEXT = TEXT-152. "United Airlines

* La fonction HIDE permet de ne pas afficher le groupe LT_STD_FCODES CALL METHOD E_OBJECT->HIDE_FUNCTIONS EXPORTING FCODES = LT_STD_FCODES.

* La fonction SHOW permet d’afficher le groupe LT_OWN_FCODES CALL METHOD E_OBJECT->SHOW_FUNCTIONS EXPORTING FCODES = LT_OWN_FCODES.

ENDMETHOD.

ENDCLASS.** lcl_event_receiver (Implementation)*===================================================================

Enfin il suffit alors de créer une instance de l’objet et de le rattacher à l’objet ALV.********* ->Create Object to receive events and link them to handler methods.* When the ALV Control raises the event for the specified instance* the corresponding method is automatically called.*

* GRID est le nom de notre composant ALV.

CREATE OBJECT EVENT_RECEIVER. SET HANDLER EVENT_RECEIVER->HANDLE_USER_COMMAND FOR GRID1. SET HANDLER EVENT_RECEIVER->HANDLE_CONTEXT_MENU FOR GRID1.*********

PAGE 91 / 92

Page 92: ALV (Fiche Technique)

Documentation sur L’ABAP List Viewer VERSION 3.1

TO DO :

1 Gestion du drag and Drop2 Listes hiérarchiques3

PAGE 92 / 92