Wednesday, November 13, 2013

PeopleCode to generate sequence number


Sometimes it's required to automatically increment the value of a sequence field when user adds a row and decrement it when a user deletes a row, through PeopleCode.

The following code is one of the solutions to this problem. It ensures that the sequence number always increments by one, and adjusts the sequence numbers accordingly if a user deletes a row, even if the row deleted is out of order.

The code goes in two events of the record field.

/*--- RowInsert ---*/
Local Rowset &Rowset;
&Rowset = GetRowset();

NS_TEST.SEQ_NUM = &Rowset.ActiveRowCount;
&Rowset.Sort(NS_TEST.SEQ_NUM, "A");


/*-- RowDelete --*/
Local Rowset &Rowset;
Local Row &Row;

&Rowset = GetRowset();
For &i = 1 To &Rowset.ActiveRowCount;
   &Row = &Rowset(&i);
   If &Row.NS_TEST.SEQ_NUM.Value > NS_TEST.SEQ_NUM.Value Then
      &Row.NS_TEST.SEQ_NUM.Value = &Row.NS_TEST.SEQ_NUM.Value - 1;
   End-If;
  
End-For;
&Rowset.Sort(NS_TEST.SEQ_NUM, "A");

No comments:

Post a Comment