Repeatable sorting on save
Pete Zagorski
It would be great if there was an option to sort repeatable records, similar to how the user can sort parent records. I have been using a data event, shown below, to sort repeatable records based on a CHOICEVALUE, but it only works when the user exits and reenters the repeatable section. If the data event could be updated so that the sort function could also be triggered immediately after a repeatable record is saved, that would also be useful.
//Replace 'sortfield_name' with the name of the field you want to sort by. Replace 'repeatable_field_name' with the name of your repeatable field
ON('change', 'repeatable_field_name', (event) => {
sortRepeats();
});
function sortRepeats() {
let reps = $repeatable_field_name || [];
let sorted = reps.sort((a, b) => {
let valueA = CHOICEVALUE(a.form_values[FIELD('sortfield_name').key]) || '';
let valueB = CHOICEVALUE(b.form_values[FIELD('sortfield_name').key]) || '';
return valueA.localeCompare(valueB);
});
rawSetValue('repeatable_field_name', sorted);
}
function rawSetValue(dataname, value) {
const field_key = FIELD(dataname).key;
var result = {
type: "set-value",
key: field_key,
value: JSON.stringify(value)
};
CONFIG().results.push(result);
}