Changing the Sort of Multiple Lines in NAV

This is a “why is this so hard” post and I’m sure I’m probably re-inventing the wheel and should try and find my year 1 computer science textbooks to look up Sort algorithms (from 20 years ago – I don’t think I still have them).

Anyway, sometimes in NAV you want to have a “Sort” order than you want to be able to change e.g. with Up Down Left Right actions, a la the Page/Report designers in the Development Environment. If you want to do one line at a time look at the Config. Package Fields page, which works fine (but isn’t obvious). If you want to allow selecting multiple lines this seems to be a lot harder (or I just struggle with it for some reason).

This is mostly a post to remind myself of the code I finally got working because it took me far too long to do this – I would be really really happy if someone can give me a better version (although in the end this is ok).

One key point is that I couldn’t get FINDSET(True,True) to behave the way I wanted it to (I don’t know why, possibly because the Key I’m using isn’t the Primary Key – I wouldn’t want it to be), so I had to do more loops than I thought.

C/AL
On Page (called by Actions):
LOCAL MoveLines(Opt : 'Up,Down,Left,Right')
CurrPage.SAVERECORD;
CurrPage.SETSELECTIONFILTER(Rec2);

Rec2.MoveSelection(Opt);

FIND;
CurrPage.UPDATE(FALSE);

On Table:
MoveSelection(Opt : 'Up,Down,Left,Right')
IF NOT FINDSET THEN 
  EXIT;

IF Opt IN [Opt::Left,Opt::Right] THEN BEGIN
  REPEAT
    CASE Opt OF
      Opt::Left: ChangeIndent(-1);
      Opt::Right: ChangeIndent(1);
    END;
  UNTIL NEXT = 0;
  EXIT;
END;

//else Up or Down
REPEAT
  TempRec := Rec;
  IF Opt = Opt::Up THEN
    TempRec.Sort -= 1
  ELSE
    TempRec.Sort += 1;
  TempRec.INSERT;  
UNTIL NEXT = 0;

RESET;
SETCURRENTKEY("Header Code",Sort);
SETRANGE("Header Code","Header Code");
n := 0;
IF FINDSET THEN REPEAT
  IF NOT TempRec.GET("Header Code","Line No.") THEN BEGIN
    TempRec.SETRANGE(Sort,n);
    WHILE TempRec.FINDFIRST DO BEGIN
      n += 1;
      TempRec.SETRANGE(Sort,n);
    END;
    TempRec := Rec;
    TempRec.Sort := n;
    TempRec.INSERT;
    TempRec.SETRANGE(Sort);
    n += 1;
  END;
UNTIL NEXT = 0;

n := 0;
TempRec.RESET;
TempRec.SETCURRENTKEY("Header Code",Sort);
TempRec.FINDSET;
REPEAT
  GET(TempRec."Header Code",TempRec."Line No.");
  Sort := n;
  MODIFY;
  n += 1;
UNTIL TempRec.NEXT = 0;
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s