KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Utility Method to Insert in a Hierarchical List AFTER a Selected Row
PRODUCT: 4D | VERSION: 16 | PLATFORM: Mac & Win
Published On: December 27, 2017

Currently in 4D the two methods available to insert in a list are APPEND TO LIST and INSERT IN LIST. The first command, APPEND TO LIST, will add a new list item to the END of a list only. The second command, INSERT IN LIST, will insert in a list BEFORE the currently selected list item.

The following utility method called Util_Insert_After will insert into a hierarchical list AFTER a selected element.

// Method: Util_Insert_After
//
// Details: Insert a list item in a hierarchical list AFTER a selected list item
//
// Input:
// $1 - (LONGINT) List to insert into
// $2 - (TEXT) Text for new item in list
// $3 - (LONGINT) Unique ref number for new item in list


C_LONGINT($1;$3;$listNum_l;$itemPos_l;$itemRef_l;$subRef_l;\
  $nextItemRef_l;$nextSubRef_l;$nextItemParentRef_l;\
  $parentPos_l;$parentItemRef_l;$newItemRef_l;$unused_l)
C_TEXT($2;$newItem_t;$unused_t)

If (Count parameters>2) // at least 3 parameters
   $listNum_l:=$1
   $newItem_t:=$2
   $newItemRef_l:=$3

     // grab other information about selected item and next item
   $itemPos_l:=Selected list items($listNum_l)
   GET LIST ITEM($listNum_l;$itemPos_l;$itemRef_l;$unused_t)
   $parentItemRef_l:=List item parent($listNum_l;$itemRef_l)
   $parentPos_l:=List item position($listNum_l;$parentItemRef_l)
   GET LIST ITEM($listNum_l;$itemPos_l+1;$nextItemRef_l;$unused_t;$nextSubRef_l)
   $nextItemParentRef_l:=List item parent($listNum_l;$nextItemRef_l)

   If ($nextItemRef_l#0) // next record exists
     If (($parentItemRef_l#0) & ($nextItemParentRef_l=0))
       GET LIST ITEM($listNum_l;$parentPos_l;$unused_l;$unused_t;$subRef_l)
       APPEND TO LIST($subRef_l;$newItem_t;$newItemRef_l)
     Else
       INSERT IN LIST($listNum_l;$nextItemRef_l;$newItem_t;$newItemRef_l)
     End if
   Else // next record does not exist
     If ($parentItemRef_l=0)
       APPEND TO LIST($listNum_l;$newItem_t;$newItemRef_l)
     Else
       GET LIST ITEM($listNum_l;$parentPos_l;$unused_l;$unused_t;$subRef_l)
       APPEND TO LIST($subRef_l;$newItem_t;$newItemRef_l)
     End if
   End if
End if

Notes about the method:
1) If the selected element is a parent element with an expanded sublist, the inserted item will be a sublist item.
  

2) If the selected element is a parent element with a collapsed sublist, the inserted item will be a parent item.
  

3) If the selected element is a parent element with no sublist, the inserted item will be a parent item.
  

4) If the selected element is a sublist item, the inserted item will be a sublist item.