Skip to content

Commit

Permalink
[ENHANCEMENT] Query String: Improve Filter Control and add prefix (fo…
Browse files Browse the repository at this point in the history
…r usage w/ multiple tables) (#1566)

* Fix: filter control not showing

* Add Query String prefix
  • Loading branch information
dansysanalyst authored May 24, 2024
1 parent 9c9a0ab commit 643da0a
Showing 1 changed file with 44 additions and 7 deletions.
51 changes: 44 additions & 7 deletions src/Concerns/Filter.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
namespace PowerComponents\LivewirePowerGrid\Concerns;

use DateTimeZone;
use Illuminate\Support\{Arr, Carbon};
use Illuminate\Support\{Arr, Carbon, Collection};
use Livewire\Attributes\On;
use PowerComponents\LivewirePowerGrid\Column;

trait Filter
{
Expand Down Expand Up @@ -330,16 +331,41 @@ public function addEnabledFilters(string $field, ?string $label): void
}
}

protected function powerGridQueryString(): array
public function listColumnForQueryString(): Collection
{
$columns = collect();

collect($this->columns())
->ensure([Column::class])
->each(function ($column) use (&$columns) {
if (isset($column->dataField)) {
$columns->put($column->dataField, $column->title ?? $column->dataField);
}

$columns->put($column->field, $column->title ?? $column->field);
});

return $columns;
}

/**
*
* @param string $prefix Prefix each field in URL
*/
protected function powerGridQueryString(string $prefix = ''): array
{
$queryString = [];

$columns = $this->listColumnForQueryString();

foreach (Arr::dot($this->filters()) as $filter) {
$as = str($filter->field)
->replace('_id', '');
->when(!empty($prefix), fn ($c) => $c->prepend($prefix . '_'))
->replace('.', '_')
->replaceMatches('/\_+/', '_');

if ($as->contains('.')) {
$as = $as->afterLast('.');
if (!empty(request()->get($as))) {
$this->addEnabledFilters($filter->field, strval($columns->get($filter->field, $filter->field)));
}

if ($filter->key === 'input_text') {
Expand All @@ -357,16 +383,27 @@ protected function powerGridQueryString(): array
}

if ($filter->key === 'number') {
$_start = $as->append('_start')->toString();
$_end = $as->append('_end')->toString();

$queryString['filters.number.' . $filter->field . '.start'] = [
'as' => $as->append('_start')->toString(),
'as' => $_start,
'except' => '',
];

if (!is_null(request()->get($_start))) {
$this->addEnabledFilters($filter->field . '_start', strval($columns->get($filter->field, $filter->field)));
}

$queryString['filters.number.' . $filter->field . '.end'] = [
'as' => $as->append('_end')->toString(),
'as' => $_end,
'except' => '',
];

if (!is_null(request()->get($_end))) {
$this->addEnabledFilters($filter->field . '_end', strval($columns->get($filter->field, $filter->field)));
}

continue;
}

Expand Down

0 comments on commit 643da0a

Please sign in to comment.