Add new row at top of sorted repeater

I want to add a new row to the top of a repeater that the user could possibly have already sorted.

For example, the repeater might have been sorted alphabetically by name, but I want the new name to be added to the top no matter where it should appear once sorted. The user would have to sort again to add that new name to it’s proper order in the sort.

Is there a way to do this?

A few ways you could think about this, depending on why you need this behavior, what else might be going on, etc…

I’ve done something like this before by showing a second repeater above the first, serving as a kind of “pre-sort list”. When new rows are added, the sort order is inverted (“Sort Repeater by [[-Repeater.index]]”) and then once new entries are accepted (in your case, a sort order is changed) a new row is added for each row in the pre-sort repeater and then the sort is applied, and all rows in the pres-sort repeater are deleted. As the pre-sort repeater size changed, the position of the final repeater was moved accordingly. There was a need to have a kind of “pre-accepted state” which may not be the case for you, though.

Another approach is to add a column to your repeater for “pre-sort” or “new entries” and perform a sort on that column right after your Add Row action, thus pushing a new entry to the top. A search in this forum turned up a good thread for this:

I modified this for your specific case in this demo .rp file:
repeater add rows to top.rp (74.7 KB)

The repeater has three main (visible) columns: Number, Name, Category. The repeater’s datasheet has four columns: Num, Name, Cat, and Pre. The Pre column is used to sort new entries to the top of the list. When a new row is added by clicking the Add button, the Pre column is assigned a negative number. I use the default global variable, OnLoadVariable to keep track of new entries by decrementing its value by 1, then adding the new row, then sorting on the Pre column. This should guarantee new entries will appear at the top of the list.

You can click the column headers to sort the repeater, and click them again to invert the sort. When a header is clicked, it marks all the rows, updates the marked rows to set the Pre column to [[TargetItem.index]] and then unmarks the rows.

To demonstrate this, I have a hidden widget in the repeater named, “indexval” which you can display by clicking the “Show Pre-Sort” button. This gives you a way to see the value of the Pre column and how the repeater is sorted. Of course, you don’t need the indexval widget or “Show Pre-Sort” button for this to work, it is just for instructional purposes.