summaryrefslogtreecommitdiff
path: root/src/TableComponent.php
diff options
context:
space:
mode:
Diffstat (limited to 'src/TableComponent.php')
-rw-r--r--src/TableComponent.php65
1 files changed, 62 insertions, 3 deletions
diff --git a/src/TableComponent.php b/src/TableComponent.php
index 0a55d5e..266cdc3 100644
--- a/src/TableComponent.php
+++ b/src/TableComponent.php
@@ -2,6 +2,8 @@
namespace Lightscale\LaralightTables;
+use Lightscale\LaralightTables\Columns\Column;
+
use Livewire\Component;
use Livewire\WithPagination;
use Livewire\Attributes\Url;
@@ -28,9 +30,19 @@ abstract class TableComponent extends Component
#[Url]
public int $pageSize;
+
public array $activeColumns = [];
- public function mount()
+ #[Url]
+ public array $filters = [];
+
+ #[Url]
+ public ?string $order = null;
+
+ #[Url]
+ public ?string $orderDirection = null;
+
+ public function mount(): void
{
$this->setDefaultActiveColumns();
$this->setDefaultPageSize();
@@ -63,6 +75,28 @@ abstract class TableComponent extends Component
}
}
+ public function updatedFilters(): void
+ {
+ $this->resetPage();
+ }
+
+ public function orderBy(string $column): void
+ {
+ if ($column === $this->order) {
+ if ($this->orderDirection === 'desc') {
+ $this->order = null;
+ $this->orderDirection = null;
+ }
+ else {
+ $this->orderDirection = 'desc';
+ }
+ }
+ else {
+ $this->order = $column;
+ $this->orderDirection = 'asc';
+ }
+ }
+
protected function toolbar(): ?Toolbar
{
return null;
@@ -91,6 +125,25 @@ abstract class TableComponent extends Component
protected function search(Builder $builder, string $search) : void {}
+ protected function getFilters(): Collection
+ {
+ return $this->getToolbar()?->getFilters() ?? collect();
+ }
+
+
+ protected function getOrderColumn(): ?Column
+ {
+ return ($name = $this->order) === null ? null : $this->getColumns()[$name] ?? null;
+ }
+
+ protected function applyOrder(Builder $query): void
+ {
+ $column = $this->getOrderColumn();
+ if ($column) {
+ $column->applySort($query, $this->orderDirection);
+ }
+ }
+
protected function buildQuery() : Builder
{
$query = $this->query();
@@ -99,16 +152,22 @@ abstract class TableComponent extends Component
$this->search($query, $this->search);
}
+ foreach ($this->getFilters() as $filter) {
+ $filter->applyFilter($query);
+ }
+
+ $this->applyOrder($query);
+
return $query;
}
private ?Collection $columnsCache = null;
- public function getColumns()
+ public function getColumns(): Collection
{
if($this->columnsCache === null) {
$this->columnsCache = collect($this->columns())->each(
fn($c) => $c->setTable($this)
- );
+ )->keyBy('name');
}
return $this->columnsCache;