Tip: Use the "+" links for multiple column sorting
Tip: Sorting has 3 states - ascending, descending and non-sorting state.
Name Surname Street address
Birthdate Weight (kg)
Martina Trommler Holmatun 44 1964-10-25 80.3
Marij Rašpolić 4094 Leslie Street 1972-12-16 75.7
Lyyli Vaara Νάξου 236 1963-05-05 102.2
Dýrleif Björnsdóttir Via Donnalbina 121 1972-11-24 91.5
Martha Yohannes Dalmatinova 70 1966-11-05 74.8
Amadi Onyekachukwu Via Vipacco 34 1981-07-09 96.9
Satu Tukio 21 Porana Place 1975-03-25 59.4
Mary Black Ægissidu 89 1994-12-15 49.2
Consuela Takens Hraunás 93 1993-01-20 81.3
Aaya Weerdenburg Via San Domenico Soriano 147 1970-05-04 67.7
Ormos Széll Parmova 55 1993-01-31 66.4
Hrvojka Petković Βερανζέρου 294 1962-09-30 82.9

Code

# SortingGrid.php

<?php

declare(strict_types = 1);

use TwiGrid\DataGrid;
use Nette\Database\Explorer;
use Nette\Database\Table\Selection;


final class SortingGrid extends DataGrid
{

	private Explorer $database;


	public function __construct(Explorer $database)
	{
		parent::__construct();

		$this->database = $database;
	}


	protected function build(): void
	{
		$this->setPrimaryKey('id');
		$this->addColumn('firstname', 'Name')->setSortable();
		$this->addColumn('surname', 'Surname')->setSortable();
		$this->addColumn('streetaddress', 'Street address');
		$this->addColumn('birthday', 'Birthdate')->setSortable();
		$this->addColumn('kilograms', 'Weight (kg)')->setSortable();

		$this->setDataLoader(function (array $filters, array $order): Selection {
			$users = $this->database->table('user');

			// sorting
			foreach ($order as $column => $dir) {
				$users->order($column . ($dir === TwiGrid\Components\Column::DESC ? ' DESC' : ''));
			}

			return $users->limit(12);
		});

		$this->setRecordVariable('user');
	}

}