Documentation sur L’ABAP List Viewer
VERSION 3.1
ALV ALV
PAGE 1 / 94
Documentation sur L’ABAP List Viewer
VERSION 3.1
SOMMAIRE : A Introduction :Comment :Comment devenir super fort pour faire des listes ........................................................... ............5 ........ ....5
A.I Introduction............................................................................................................... Introduction...................................................................................................................................................5 ....................................5 A.II Fondements théoriques............................................................................................................................. théoriques............................................................................................................................. ..5 B Réalisation technique ALV STANDARD:............................................................................................... STANDARD:...........................................................................................................6 ............6
B.I Présentation Générale :................................................................................................................................6 B.I.1 Schéma général........................................................................................................................................6 B.I.2 Définition des différentes éléments:.........................................................................................................6 B.I.2.a Ecran – Screen painter.......................................................................................................................6 B.I.2.b Container...........................................................................................................................................6 B.I.2.c Grille ALV.........................................................................................................................................7 ALV.........................................................................................................................................7 B.I.2.d Classe des évènements :....................................................................................................................7 B.I.2.e Catalogue : ........................................................................................................................................7 B.II L’écran – le screen painter.........................................................................................................................8 B.III Le catalogue............................................................................................................................................ catalogue............................................................................................................................................ ..10 B.III.1 Définition............................................................................................................................................ Définition............................................................................................................................................ .10 B.III.2 Méthode automatique :........................................................................................................................10 B.III.3 Méthode manuelle...............................................................................................................................10 B.III.3.a Processus :.....................................................................................................................................10 B.III.3.b Exemple de création du catalogue................................................................................................11 B.III.4 Méthode semi-automatique.................................................................................................................12 B.III.4.a Processus :.....................................................................................................................................12 B.III.5 Exemple...............................................................................................................................................12 B.III.6 Catalogue – Quantité et currency........................................................................................................13 B.III.6.a Gestion des devises : (voir doc SAP)............................................................................................13 B.III.6.b Gestion des quantités : (Voir doc SAP)........................................................................................13 B.IV Le container..............................................................................................................................................14 B.IV.1 Paramètres :.........................................................................................................................................14 B.V Gestion du layout ......................................................................................................................................15 B.V.1 Options principales...............................................................................................................................15 B.V.2 Gestion des couleurs ............................................................................................................................15 B.V.2.a Gestion de colonne en couleur.......................................................................................................15 B.V.2.b Gestion de la couleur pour les lignes.............................................................................................15 B.V.2.c Gestion de la couleur pour des cellules..........................................................................................16 B.V.2.d Affichage zébré des lignes.............................................................................................................16 B.VI Gestion variantes.................................................................................................................................... variantes.................................................................................................................................... ..17 B.VII Les évènements.......................................................................................................................................19 B.VII.1 Définition :.........................................................................................................................................19 B.VII.2 Implémentation :................................................................................................................................20 B.VII.3 Utilisation :.........................................................................................................................................21 B.VIII La grille ou composant ALV........................................................................................................... ALV........................................................................................................... .....23 B.VIII.1 Définition :........................................................................................................................................23 B.VIII.2 Création de l’objet :..........................................................................................................................23 B.VIII.3 La fonction set_table_for_first_display............................................................................................23 B.VIII.4 La fonction refresh_table_display....................................................................................................28 B.VIII.5 La fonction set_focus........................................................................................................................28 B.VIII.6 Exemple :..........................................................................................................................................29 B.IX Gestion avec plusieurs ALV............................................................................................................... ALV............................................................................................................... .....31 B.X REALISATION PRATIQUE : Exemple................................................................................................ Exemple................................................................................................ .32 B.X.1 MISE EN ŒUVRE...............................................................................................................................32 B.X.2 EXEMPLES..........................................................................................................................................32
PAGE 2 / 94
Documentation sur L’ABAP List Viewer
VERSION 3.1
C Utilisation des fonctions ALV définies pas SAP...............................................................................................47
C.I Fonction Standart SAP pour une ALV rapide.........................................................................................47 rapide.........................................................................................47 C.I.1 Affichage d’un ALV simple............................................................. simple...................................................................................................................47 ......................................................47 C.I.1.a Appel de base de la fonction REUSE_ALV_LIST_DISPLAY .....................................................47 C.I.1.b Définition de la fonction.................................................................................................................47 C.II Liste hiérarchique ....................................................................................................................................49 C.II.1 Introduction : ........................................................................................................................................49 C.II.2 Clé de correpondance............................................................................................................................49 C.II.3 Layout...................................................................................................................................................49 C.II.3.a Gestion de l’expansion...................................................................................................................50 C.II.3.b Gestion des LED............................................................................................................................50 C.II.3.c Gestion des checkbox............................................................... checkbox.....................................................................................................................50 ......................................................50 C.II.3.d Affichage du détail ........................................................................................................................50 C.II.3.e Autres possibilités..........................................................................................................................51 C.III Liste sous forme de grille........................................................................................................................52 C.IV Le catalogue............................................................................................. catalogue............................................................................................................................................ ............................................... ..53 C.IV.1 Définition du catalogue.......................................................................................................................53 C.IV.2 Déclaration :........................................................................................................................................53 C.IV.3 Zone en entrée.....................................................................................................................................54 C.IV.4 EXAMPLE d’implémentation manuelle.............................................................................................54 C.V Gestion du menu et de la barre des boutons........................................................................................ ...56 C.V.1.a Gestion des codes Transactions et clik de la souris.......................................................................56 C.VI Gestion des variantes...............................................................................................................................58 C.VI.1 Définition.............................................................................................................................................58 Définition.............................................................................................................................................58 C.VI.2 Implémentation....................................................................................................................................58 C.VI.3 Fonction utiles.....................................................................................................................................58 C.VI.3.a Gestion du F4................................................................................ F4................................................................................................................................58 ................................................58 C.VI.3.b Sauvegarde de la variante dans le PAI (A vérifier)......................................................................58 C.VI.3.c Récupération de la variante par défaut.........................................................................................59 C.VII Table contenant les données............................................................................................................... données............................................................................................................... ...60 C.VIII Les événements........................................................................................................................ événements......................................................................................................................................61 ..............61 C.IX Commentaires : Entête de page..............................................................................................................63 C.X Gestion de plusieurs ALV sur un seul écran ..........................................................................................64 C.X.1 Initialisation..........................................................................................................................................64 C.X.2 Définition des blocs..............................................................................................................................65 C.X.2.a ALV classique :..............................................................................................................................65 C.X.2.b Alv Hiérarchique :.........................................................................................................................65 C.X.3 Affichage des blocs............................................................................... blocs...............................................................................................................................65 ................................................65 C.X.4 Gestion des extraits – sauvegarde de table interne...............................................................................67 C.X.4.a Initialisation...................................................................................................................................67 C.X.4.c Aide F4........................................................................................... F4...........................................................................................................................................68 ................................................68 C.X.4.d Enregistrement de l’extrait............................................................................................................68 C.X.4.e Chargement de l’ extrait...................................................................................... extrait..................................................................................................................68 ............................68 C.X.4.f Exemple......................................................................................................................................... Exemple......................................................................................................................................... .68 D ANNEXES :............................................................................. :........................................................................................................................................................71 ...........................................................................71
D.I Utilisation de classe sous SAP....................................................................................................................72 D.I.1 Déclaration d’une classe........................................................................................................................72 D.I.2 Exemple de définition de classe.............................................................................................................72 D.I.3 Implémentation d’une classe..................................................................................................................73 E Annexe sur ALV standard..................................................................................................................................74 standard..................................................................................................................................74
E.I Gestion des groupes de colonnes pour les variantes :............................................................................. .74 E.II Ajout d’un menu........................................................................................................................................75
PAGE 3 / 94
Documentation sur L’ABAP List Viewer
VERSION 3.1
E.III Output Options of Columns.................................................................................................................. ..79 E.IV Formatting Column Contents ................................................................................................................81 E.V Properties of the Grid Control ................................................................................................................83 E.VI Events of Class CL_GUI_ALV_GRID ..................................................................................................85 E.VII Découpage de l’écran afin d’afficher plusieurs ALV......................................................................... .87 E.VII.1 Définition de l ’écran de sélection.......................................................................................................87 E.VIII Affichage d’un objet ALV sans utiliser de screen Painter ......................................................... ......89 E.IX Définir un menu contextuel : Bouton droit de la souris.......................................................................90 TO DO :.............................................................................................................................................................. ..94
PAGE 4 / 94
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’A bap 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 5 / 94
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. CONTAINER DE RECEPTION
GRILLE ALV
P a r a m è r t e s :
LAYOUT VARIANTE CATALOGUE
Objet attaché : EVENEMENT
B.I.2 Définition des différentes éléments:
B.I.2. A E CRAN – S CREEN 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 C ONTAINER 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 6 / 94
Documentation sur L’ABAP List Viewer
VERSION 3.1
B.I.2.C G RILLE ALV Ce 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 C LASSE 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 C ATALOGUE : Ce dernier correspond à une table interne et définit entièrement les informations relatives à l’affichage des champs dans l’ALV.
PAGE 7 / 94
VERSION 3.1
Documentation sur L’ABAP List Viewer
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 8 / 94
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.
Custom contrôle
Nom de l’objet
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 9 / 94
Documentation sur L’ABAP List Viewer
B.III
VERSION 3.1
Le catalogue
Aide SAP : SAP Library Basis components Basis services / communication interface (BC-SRV) Abap list viewer (BC-SRV-ARL) BC-ALV Grid Control
B.III.1 Définition Lors 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 manuelle Tous 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. A P ROCESSUS : 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 REF_TABLE
Correspond au nom du champ de référence. Ex ‘NAME1’ Correspond à la table de référence. Ex ‘KNA1’
PAGE 10 / 94
VERSION 3.1
Documentation sur L’ABAP List Viewer Les intitulés sont alors directement récupérés et ne peuvent pas être modifiés.
Spécifique: COLTEXT TEXTE TOOLTIP SELTEXT Définition DATATYPE du champ : INTTYPE DATATYPE ou INTTYPE OUTPUTLEN
Intitulé de la colonne Intitulé de la bulle d’aide Intitulé du texte Type de donnée : DEC, CHAR Type de donnée élémentaire C, I Largeur de la colonne
Il peut être utile dans le cas de champs spécifique d’utiliser des routines de conversion d’entréesortie. On utilise alors le champ
If you set a conversion exit (for example, conv = ' ==ALPHA ' for function module CONVERSION_EXIT_ALPHA_OUTPUT ), you enforce output conversion for the EDIT_MASK associated output field. (See also F1 help for WRITE edit option USING EDIT MASK) .
Commun :
Nom du champ FIELDNAME
Désignation 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) Position de la colonne.
COL_POS
B.III.3.B E XEMPLE 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 11 / 94
VERSION 3.1
Documentation sur L’ABAP List Viewer
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. A P ROCESSUS : 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
structure de la table contenant les données à afficher la table interne correspondant au catalogue la
3. Ajout de champs spécifiques se fait alors manuellement : Nom du champ CLEAR GT_FIELDCAT. GT_FIELDCAT-FIELDNAME GT_FIELDCAT-COL_POS GT_FIELDCAT-COLTEXT GT_FIELDCAT-TOOLTIP GT_FIELDCAT-SELTEXT
Exemple de valeur
Désignation
= 'ECART'. = '12'. = 'ECART.'(100). = 'ECART.'(101). = 'ECART.'(102).
GT_FIELDCAT-DATATYPE
= 'DEC'.
GT_FIELDCAT-OUTPUTLEN APPEND GT_FIELDCAT.
= 13.
Nom du champ Position de la colonne dans l’ALV Intitulé de la colonne Intitulé de la Bulle d’aide Intitulé de la colonne lors d’un passage de la souris Type de donnée (Pour les données de base on utilise le champ INTTYPE) Taille de la colonne en sortie
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
PAGE 12 / 94
Documentation sur L’ABAP List Viewer
VERSION 3.1
READ TABLE GT_FIELDCAT WITH KEY FIELDNAME = 'WERKS'. 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. A G ESTION DES DEVISES : ( VOIR DOC SAP) Dans le cas, où l’on affiche des valeurs nécessitant un formatage selon une devise, on peut : o o
Soit utiliser le champ CURRENCY pour une devise fixe pour toute la colonne. Soit CFIELDNAME faisant référence à un autre champ (de type devise telles que DEM ou USD) du Catalogue.
B.III.6.B G ESTION DES QUANTITÉS : (V OIR DOC SAP) Dans le cas, où l’on affiche des valeurs nécessitant un formatage selon une quantité, on peut : o o
Soit utiliser le champ QUANTITY pour une devise fixe pour toute la colonne. Soit QFIELDNAME faisant référence à un autre champ (de type unit tel que KG) du Catalogue.
PAGE 13 / 94
Documentation sur L’ABAP List Viewer
B.IV
VERSION 3.1
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 container DATA 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 14 / 94
VERSION 3.1
Documentation sur L’ABAP List Viewer
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 Grid_title Sel_mode CWIDTH_OPT NO_TOOLBAR
Désignation Défini le titre Sélection de multi-ligne Ajuste la taille des colonnes selon le contenu. 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 G ESTION 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 G ESTION 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 . DATA:
linecolor(4) type c. "Color for corresponding line
DATA: END OF GT_OUTTAB.
PAGE 15 / 94
VERSION 3.1
Documentation sur L’ABAP List Viewer
2 Renseigner le champ INFO_NAME de la structure. GT_CATALOG-INFO_NAME = linecolor.
B.V.2.C G ESTION 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 16 / 94
VERSION 3.1
Documentation sur L’ABAP List Viewer
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
Loading delivered display variants 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.
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 =
I_SAVE = SPACE. (default setting)
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 = 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 17 / 94
VERSION 3.1
Documentation sur L’ABAP List Viewer 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 18 / 94
VERSION 3.1
Documentation sur L’ABAP List Viewer
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 double_click e_row e_column
-> nom de la fonction -> Nom de l’évènement (voir annexe) -> Paramètres récupérés (voir définition de l’évènement)
PAGE 19 / 94
VERSION 3.1
Documentation sur L’ABAP List Viewer
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 20 / 94
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 21 / 94
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 22 / 94
Documentation sur L’ABAP List Viewer
B.VIII
VERSION 3.1
La grille ou composant ALV
Le 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 23 / 94
VERSION 3.1
Documentation sur L’ABAP List Viewer Cette dernière utilise plusieurs paramètres:
CALL METHOD grid1->set_table_for_first_display EXPORTING I_STRUCTURE_NAME IS_VARIANT I_SAVE I_DEFAULT IS_LAYOUT IS_PRINT IT_SPECIAL_GROUPS IT_TOOLBAR_EXCLUDING
= = = = = = = =
< < < < < < < <
string of type DD02L-TABNAME> structure of type DISVARIANT> var. of type CHAR01> var. of type CHAR01> structure of type LVC_S_LAYO> structure of type LVC_S_PRNT> internal table of type LVC_T_SGRP> internal table of type UI_FUNCTIONS>
CHANGING IT_OUTTAB IT_FIELDCATALOG IT_SORT IT_FILTER
= = = =
< < < <
internal table> internal table of type LVC_T_FCAT> internal table of type LVC_T_SORT> 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 24 / 94
VERSION 3.1
Documentation sur L’ABAP List Viewer EXPORTING Type
Nom du paramètre I_STRUCTURE_NAME
CATALOGUE
IS_VARIANT I_SAVE
I_DEFAULT
VARIANTE
IT_SPECIAL_GROUPS
LAYOUT IMPRESSION
Désignation Nom de la structure du catalogue si elle appartient au dictionnaire ex : SFLIGHT Nom de la variante Autres paramètres propre à la gestion des variantes Autes paramètres propre à la gestion des variantes Permet de définir des groupes de colonnes (voir annexe)
IS_LAYOUT
Nom du layout
IS_PRINT
Structure définissant les paramètres d’impression de l’ALV.
IT_OUTTAB IT_FIELDCATALOG
Nom de la table interne Nom du catalogue si spécifique
IT_SORT
Table interne contenant les informations de tri
CHANGING
TABLE DONNEES CATALOGUE TRI FILTRE
IT_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 25 / 94
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 26 / 94
VERSION 3.1
Documentation sur L’ABAP List Viewer 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 27 / 94
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_display
Cette fonction permet de réinitialiser l’objet ALV.
call method grid1->refresh_table_display.
B.VIII.5
La fonction set_focus
Cette méthode permet de sélectionner l’objet actif dans l’écran, dans l’exemple qui suit on choisit grid1.
PAGE 28 / 94
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 . 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 29 / 94
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 30 / 94
Documentation sur L’ABAP List Viewer ENDMODULE.
B.IX
VERSION 3.1
" PBO_100 OUTPUT
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 31 / 94
Documentation sur L’ABAP List Viewer
B.X
VERSION 3.1
REALISATION PRATIQUE : Exemple
Voici 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 EXEMPLES Exemple de programme simple avec un seul ALV :
program bcalvc_variants_exe. *&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& &&&&&& * Purpose: * ~~~~~~~~
PAGE 32 / 94
Documentation sur L’ABAP List Viewer
VERSION 3.1
* This example illustrates how a variant can be chosen before * 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 b ind 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 33 / 94
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 34 / 94
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
PAGE 35 / 94
VERSION 3.1
Documentation sur L’ABAP List Viewer 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 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 36 / 94
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 . 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 . ************** ** ENTETE data : 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,
PAGE 37 / 94
Documentation sur L’ABAP List Viewer
VERSION 3.1
* Nom du contenair principal 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_fcat with header line, gt_field_cat_poste type lvc_t_fcat with 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 38 / 94
VERSION 3.1
Documentation sur L’ABAP List Viewer * 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 39 / 94
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 ********************************************************
PAGE 40 / 94
Documentation sur L’ABAP List Viewer
VERSION 3.1
form f_facture . 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
PAGE 41 / 94
Documentation sur L’ABAP List Viewer
VERSION 3.1
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. *********************************************************************** ******** * ->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.
PAGE 42 / 94
Documentation sur L’ABAP List Viewer
VERSION 3.1
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. 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
PAGE 43 / 94
Documentation sur L’ABAP List Viewer
VERSION 3.1
exporting i_parent = custom_container2. * * change title * gs_layout-grid_title = 'Liste des p ostes'(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.
PAGE 44 / 94
Documentation sur L’ABAP List Viewer
VERSION 3.1
case ok_code. 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 45 / 94
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 46 / 94
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 47 / 94
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 48 / 94
Documentation sur L’ABAP List Viewer
C.II
VERSION 3.1
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 correpondance Afin 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 Layout Le 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 49 / 94
Documentation sur L’ABAP List Viewer
VERSION 3.1
C.II.3. A G ESTION 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 G ESTION DES LED Souvent 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 G ESTION 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 50 / 94
Documentation sur L’ABAP List Viewer
VERSION 3.1
C.II.3.E AUTRES POSSIBILITÉS Key_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 51 / 94
Documentation sur L’ABAP List Viewer
C.III
VERSION 3.1
Liste sous forme de grille
Le 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 52 / 94
VERSION 3.1
Documentation sur L’ABAP List Viewer
C.IV
Le catalogue
C.IV.1 Définition du catalogue Le 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_ALV Ces 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 row_pos col_pos fieldname tabname ref_fieldname ref_tabname currency(5) cfieldname ctabname quantity(3) qfieldname qtabname roundfieldname roundtabname round decimalsfieldname decimalstabname decimals_out(6) text_fieldname exponent(3) key(1) icon(1) Symbol(1) checkbox(1) just(1) lzero(1) no_sign(1) no_zero(1) edit_mask
Définition like sy-curow like sy-cucol type slis_fieldname type slis_tabname like dd03p-fieldname like dd03p-tabname type c type slis_fieldname type slis_tabname type c type slis_fieldname type slis_tabname type slis_fieldname type slis_tabname type i type slis_fieldname type slis_tabname type c type slis_fieldname type c type c type c type c type c type c type c type c type c type slis_edit_mask
Désignation output in row position of the column
Field with currency unit and table Field with quantity unit and table
Round in write statement
" decimals in write statement exponent for floats column with key-color As icon As symbol As checkbox (R)ight (L)eft (C)ent. leading zero Write no-sign Write no-zero
PAGE 53 / 94
VERSION 3.1
Documentation sur L’ABAP List Viewer emphasize(4) fix_column(1) do_sum(1) no_out(1) tech(1) outputlen Offset seltext_l seltext_m seltext_s reptext_ddic ddictxt(1) rollname datatype inttype ddic_outputlen Intlen lowercase key_sel(1) no_sum(1) sp_group(4) Reprep(1) input(1) hotspot(1)
type c type c type c type c type c like dd03p-outputlen type dd03p-intlen like dd03p-scrtext_l like dd03p-scrtext_m like dd03p-scrtext_s like dd03p-reptext type c like dd03p-rollname like dd03p-datatype like dd03p-inttype like dd03p-outputlen like dd03p-intlen like dd03p-lowercase type c type c type c type c type c type c
Emphasize Spalte fixieren sum up (O)blig.(X)no out technical field Offset long key word middle key word Short key word heading (ddic) (S)hort (M)iddle (L)ong
Field not obligatory Do not sum up Group specification selection for rep/rep Input Hotspot
C.IV.3 Zone en entrée Il 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 54 / 94
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 55 / 94
Documentation sur L’ABAP List Viewer
C.V
VERSION 3.1
Gestion du menu et de la barre des boutons
Le 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 G ESTION DES CODES T RANSACTIONS 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 56 / 94
VERSION 3.1
Documentation sur L’ABAP List Viewer 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 TABINDEX SUMINDEX ENDSUM SEL_TAB_FIELD VALUE BEFORE_ACTION AFTER_ACTION REFRESH IGNORE_MULTI COL_STABLE ROW_STABLE EXIT FIELDNAME GROUPLEVEL COLLECT_FROM COLLECT_TO
C I I C C C C C C C C C C C I I I
30 4 4 1 60 60 1 1 1 1 1 1 1 30 4 40 4
CT_ITEM 1 0 CT_ITEM-MATNR 65
MATNR 0 0
PAGE 57 / 94
Documentation sur L’ABAP List Viewer
C.VI
VERSION 3.1
Gestion des variantes
C.VI.1 Définition * Déclaration data : gs_variant type disvariant, g_save value 'A'.
"for parameter IS_VARIANT
C.VI.2 Implémentation * Implémentation clear 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 G ESTION DU F4 Afin 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 S AUVEGARDE 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.
PAGE 58 / 94
Documentation sur L’ABAP List Viewer
VERSION 3.1
endif.
C.VI.3.C RÉ CUPÉRATION DE LA VARIANTE PAR DÉFAUT Pour 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 59 / 94
Documentation sur L’ABAP List Viewer
C.VII
VERSION 3.1
Table contenant les données
La 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 chargement data : 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 60 / 94
Documentation sur L’ABAP List Viewer
C.VIII
VERSION 3.1
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 suivante REUSE_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 61 / 94
VERSION 3.1
Documentation sur L’ABAP List Viewer Définition des constantes utilisées dans le type-spool SLIS : * Events slis_ev_item_data_expand slis_ev_reprep_sel_modify slis_ev_caller_exit_at_start slis_ev_user_command slis_ev_top_of_page slis_ev_top_of_coverpage slis_ev_end_of_coverpage slis_ev_foreign_top_of_page slis_ev_foreign_end_of_page slis_ev_pf_status_set slis_ev_list_modify slis_ev_top_of_list slis_ev_end_of_page slis_ev_end_of_list slis_ev_after_line_output slis_ev_before_line_output slis_ev_subtotal_text
type slis_formname value type slis_formname value type slis_formname value type slis_formname value type slis_formname value type slis_formname value type slis_formname value type slis_formname value type slis_formname value type slis_formname value type slis_formname value type slis_formname value type slis_formname value type slis_formname value type slis_formname value type slis_formname value type slis_formname value
'ITEM_DATA_EXPAND', 'REPREP_SEL_MODIFY', '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', '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 62 / 94
Documentation sur L’ABAP List Viewer
C.IX
VERSION 3.1
Commentaires : Entête de page
On 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 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[]. 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’. 1’. ls_line-info = ‘Texte d information’. information’. append ls_line to e04_lt_top_of_page. ls_line-key = ‘Clé 2’. 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’. liste’. append ls_line to e04_lt_top_of_page. endform.
PAGE 63 / 94
Documentation sur L’ABAP List Viewer
C.X
VERSION 3.1
Gestion de de pl plusieurs AL ALV su sur un un sseeul éc écran
(programme BALVBT01) 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 C.X.1 Initi Initiali alisat sation ion La 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 '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 64 / 94
VERSION 3.1
Documentation sur L’ABAP List Viewer
C.X.2 C.X.2 Défini Définitio tion n des blocs 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 A ALV CLASSIQUE : call function 'REUSE_ALV_BLOCK_LIST_APPEND 'REUSE_ALV_BLOCK_LIST_APPEND'' exporting * CATALOGUE it_fieldcat * LAYOUT is_layout
= xfield = x_layout
* TABLE INTERNE i_tabname *EVENEMENT it_events i_text tables t_outtab
= 'XDATA' = gt_xevents = ‘first block’ = xdata.
C.X.2.B ALV H IÉRARCHIQUE IÉRARCHIQUE : call function 'REUSE_ALV_BLOCK_LIST_HS_APPEND '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 C.X.3 Affic Affichag hage e des bloc blocs s Enfin, afin de pouvoir afficher tout les blocs à l’écran il suffit alors d’appeler la fonction suivante :
PAGE 65 / 94
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 66 / 94
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 I NITIALISATION Il 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.B La 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 extraits C_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 67 / 94
Documentation sur L’ABAP List Viewer
VERSION 3.1
CS_EXTRACT1 = GS_EXTRACT1 CS_EXTRACT2 = GS_EXTRACT2.
C.X.4.C AIDE F4 On 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 E NREGISTREMENT 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 C HARGEMENT DE L’ EXTRAIT call function 'REUSE_ALV_EXTRACT_LOAD' exporting is_extract = gs_extract2 tables et_exp01 = gt_sflight.
C.X.4.F E XEMPLE REPORT BALVEX01 NO STANDARD PAGE HEADING. * DB-Table TABLES SFLIGHT. * Type-pool of ALV TYPE-POOLS: SLIS. * Report Selections SELECT-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.
PAGE 68 / 94
Documentation sur L’ABAP List Viewer
VERSION 3.1
parameters: p_save radiobutton group extr. 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 displayed DATA: 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 request AT 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
PAGE 69 / 94
Documentation sur L’ABAP List Viewer
VERSION 3.1
C_P_EXT2 = P_EXT2 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 70 / 94
Documentation sur L’ABAP List Viewer
VERSION 3.1
D ANNEXES :
PAGE 71 / 94
VERSION 3.1
Documentation sur L’ABAP List Viewer
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 Programming Abap Objects
D.I.1 Déclaration d’une classe Les classes sous SAP se décomposent en trois parties : • • •
Public : Privé : Protected :
accessible par tous accessible uniquement par les objets de l a classe 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.
PAGE 72 / 94
Documentation sur L’ABAP List Viewer
VERSION 3.1
ENDCLASS.
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 73 / 94
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 74 / 94
VERSION 3.1
Documentation sur L’ABAP List Viewer
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 75 / 94
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 declaration include vsd03top.
* Initialization fieldcatalog initialization. g_repid = sy-repid. perform fieldcat_init using gt_fieldcat[]. * Data selection start-of-selection. perform select_data tables gt_outtab. * Display list end-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 76 / 94
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 77 / 94
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 78 / 94
Documentation sur L’ABAP List Viewer
E.III Field name
VERSION 3.1
Output Options of Columns 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:
HOTSPOT KEY
LOWERCASE
NO_OUT
NO_SUM OUTPUTLEN
•
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. LVC_HOTSPT Char(1) SPACE, 'X' If this field is set, all cells of this column are hotspot-sensitive. 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 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. 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. LVC_NOSIGN Char(1) SPACE, 'X' If you set this field, you lock totals calculation for the relevant field. LVC_OUTLEN Numc(6) 0 (default setting), n
PAGE 79 / 94
Documentation sur L’ABAP List Viewer
VERSION 3.1
Determines the column width of the field: •
•
TECH
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.
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 80 / 94
Documentation sur L’ABAP List Viewer
E.IV
VERSION 3.1
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 @ ). 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:
LZERO
•
'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. LVC_LZERO Char(1) SPACE, 'X' 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
PAGE 81 / 94
Documentation sur L’ABAP List Viewer
NO_SIGN
NO_ZERO
ROUND
ROUNDFIELD
SYMBOL
VERSION 3.1
zeros are displayed. 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). LVC_NOZERO Char(1) SPACE, 'X' If NO_ZERO is set, no zeros are displayed for initial value fields. The cell remains empty. LVC_ROUND Char(10) initial, natural number Displaying 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) 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. 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 82 / 94
VERSION 3.1
Documentation sur L’ABAP List Viewer
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'
Set the selection mode (see table below).
SPACE, 'A', 'B', 'C', 'D'
SEL_MODE
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)
'B'
'C'
Simple selection, list box
Multiple selection, list
•
•
•
Multiple columns Multiple rows
The user selects the rows through pushbuttons at the left border of the grid control.
Multiple columns
•
Multiple rows
•
Multiple
PAGE 83 / 94
Documentation sur L’ABAP List Viewer box
columns •
'D'
Cell selection
VERSION 3.1
•
Multiple rows 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 84 / 94
Documentation sur L’ABAP List Viewer
E.VI
VERSION 3.1
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 85 / 94
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 86 / 94
Documentation sur L’ABAP List Viewer
E.VI E.VIII
VERSION 3.1
Déco Découp upag agee de de l’é l’écr cran an afin afin d’af d’affi fich cher er plus plusie ieur urss ALV ALV..
E.VII.1
Définition de l’écran de sélection
Afin 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 util utilis ise e tou toujo jour urs s un un obj objet et de type type « cus custo tom_ m_co cont ntai aine nerr » rat ratta tach ché é au au « cutom_control » de l’écran.
2
On crée créerr alo alors rs un obje objett de de type type « spl split itte ter_ r_cu cust stom om » rat ratta tach cher er au au « cust custom om_c _con onta tain iner er » définit précédemment.
3
On peut peut alo alors rs soit soit déf défin inir ir des des cont contén énai aire res s et y atta attach cher er les les obje objets ts ALV ALV,, soi soitt ratt rattac acher her 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 87 / 94
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, cl_gui_alv_grid, grid2 type ref to cl_gui_alv_grid. 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 container create object custom_splitter exporting * Nombre de lignes rows = 1 * Nombre de colones columns = 2 * Le parent est le contenair définit précedement parent = 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 88 / 94
VERSION 3.1
Documentation sur L’ABAP List Viewer
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 dock_at_left dock_at_top dock_at_bottom dock_at_right property_docking
Type / Value Type I Value 1 Type I Value 2 Type I Value 4 Type I Value 8 Type I Value 470
Description / Use Left-hand edge of the screen Top edge of the screen Bottom edge of the screen Right-hand edge of the screen Docking property
property_floating
Type I Value 480
Floating property
PAGE 89 / 94
VERSION 3.1
Documentation sur L’ABAP List Viewer
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 SE41 constants: 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
ADD_FUNCTION
= p_menu.
Adds a function : CALL METHOD E_OBJECT->ADD_FUNCTION EXPORTING FCODE = 'AA' “code fonction TEXT = TEXT-150.
ADD_MENU ADD_SUBMENU
ADD_SEPARATOR
"American Airlines
Adds a menu that you defined in the Menu Painter 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. Adds a separator call method p_menu->add_separator.
RESET HIDE FUNCTIONS
Reset to initial value Hides a function DATA: LT_STD_FCODES TYPE UI_FUNCTIONS. * Fonction standard ALV
PAGE 90 / 94
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 function DATA: LT_STD_FCODES TYPE UI_FUNCTIONS. * Fonction standard ALV 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->SHOW_FUNCTIONS EXPORTING FCODES = LT_STD_FCODES.
DISABLE_FUNCTIONS ENABLE_FUNCTIONS
Inactivates a function 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 . ********* * 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,
PAGE 91 / 94
VERSION 3.1
Documentation sur L’ABAP List Viewer LT_OWN_FCODES TYPE UI_FUNCTIONS.
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 cua_status value 'CT_STATIC'.
value 'CTMENU_BUILD',
c_status_context type
* Chargement d’un menu définit dans le menu painter call 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.
PAGE 92 / 94
Documentation sur L’ABAP List Viewer
VERSION 3.1
APPEND 'LH' TO LT_OWN_FCODES. 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 93 / 94