Page 1 of 1

Browse sort using another field

Posted: Mon Sep 18, 2023 8:22 am
by mih
When clicking on field header in browse form is it possible to use other field (not that from clicked header)?

Example: I have field , call it "Num" with numbers, format of numbers like "1-2022", "2-2022", "12-2023" and so on. Then sorting straight by numbers we receive sequence "1-2022", "12-2023", "2-2022". I can make calculated field in browse query like "2022001", "2022002", "2023012 " and hide it by width 0.
How to use this hidden field to sort rows, when clicking on "Num" header?

Re: Browse sort using another field

Posted: Mon Sep 18, 2023 9:46 am
by kev1n
Hi,

The easiest method would probably be to initially display the values in the format 2022001 and then use JavaScript to reformat them as needed. This approach ensures that sorting functions correctly since the formatting aligns with the original value, such as 2022001.

Code to be added in Custom Code / Browse section:

Code: Select all

function convertDateFormat(input) {
	const dateRegex = /^(\d{4})0(\d{2})$/;

	if (!dateRegex.test(input)) {
		return "Invalid input format";
	}

	const [, year, month] = input.match(dateRegex);
	const formattedMonth = month.startsWith('0') ? month.slice(1) : month;

	return `${formattedMonth}-${year}`;
}

function formatColumns() {
  
	const column = 1; // which column to format. 0 = first column, 1 = 2nd column etc.
	const $columnElements = $(`[data-nu-column='${column}']`);

	$columnElements.each(function() {
		const value = $(this).html();
		if (value) {
			$(this).html(convertDateFormat(value));
		}
	});
}

formatColumns();

Re: Browse sort using another field

Posted: Mon Sep 18, 2023 5:01 pm
by mih
Thanks, it works!
Those are not months - just number, up to 999.
Also change regexp to /^(\d{4})0*(\d+)$/

Please move topic to "Custom code" so solution was as "Custom code".