|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Rappasoft\LaravelLivewireTables\Views\Traits; |
| 4 | + |
| 5 | +use Livewire\Attributes\{Modelable,On,Renderless}; |
| 6 | + |
| 7 | +trait IsExternalArrayFilter |
| 8 | +{ |
| 9 | + #[Modelable] |
| 10 | + public array $value = []; |
| 11 | + |
| 12 | + public string $filterKey = ''; |
| 13 | + |
| 14 | + public string $tableName = ''; |
| 15 | + |
| 16 | + public string $tableComponent = ''; |
| 17 | + |
| 18 | + protected bool $needsUpdating = false; |
| 19 | + |
| 20 | + protected array $returnValues = []; |
| 21 | + |
| 22 | + public array $selectedItems = []; |
| 23 | + |
| 24 | + public array $selectOptions = []; |
| 25 | + |
| 26 | + #[On('filter-was-set')] |
| 27 | + public function setFilterValues(string $tableName, string $filterKey, array $value): void |
| 28 | + { |
| 29 | + if ($tableName == $this->tableName && $filterKey == $this->filterKey && $this->selectedItems != $value) { |
| 30 | + $this->selectedItems = $value; |
| 31 | + $this->needsUpdating = false; |
| 32 | + |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + protected function clearFilter() {} |
| 37 | + |
| 38 | + #[Renderless] |
| 39 | + public function updatedSelectedItems(string $value): void |
| 40 | + { |
| 41 | + if (! $this->needsUpdating) { |
| 42 | + $this->needsUpdating = true; |
| 43 | + |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + #[Renderless] |
| 48 | + protected function sendUpdateDispatch(array $returnValues): void |
| 49 | + { |
| 50 | + if ($this->needsUpdating) { |
| 51 | + if (! empty($returnValues)) { |
| 52 | + $this->value = array_keys($returnValues); |
| 53 | + } else { |
| 54 | + $this->value = []; |
| 55 | + } |
| 56 | + $this->dispatch('livewireArrayFilterUpdateValues', tableName: $this->tableName, filterKey: $this->filterKey, values: $returnValues)->to($this->tableComponent); |
| 57 | + |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + #[Renderless] |
| 62 | + public function renderingIsExternalArrayFilter(): void |
| 63 | + { |
| 64 | + $returnValues = []; |
| 65 | + |
| 66 | + if ($this->needsUpdating == true && ! empty($this->selectedItems)) { |
| 67 | + foreach ($this->selectedItems as $selectedItem) { |
| 68 | + $returnValues[$selectedItem] = $this->selectOptions[$selectedItem] ?? 'Unknown'; |
| 69 | + } |
| 70 | + $this->sendUpdateDispatch($returnValues); |
| 71 | + } |
| 72 | + } |
| 73 | +} |
0 commit comments