From 32f800e915956c41f2562a3f080632b1cd87cdaa Mon Sep 17 00:00:00 2001 From: Mystical0628 <120995016+Mystical0628@users.noreply.github.com> Date: Fri, 13 Sep 2024 01:44:13 +0300 Subject: [PATCH] Feature/filters autofill (#2895) * Allow to pass to display() not only Field`s but also Group`s * Add Autofill trait for Filter * Add test --- src/Filters/Filter.php | 17 ++++++++++++++--- tests/Unit/Screen/Layouts/SelectionTest.php | 20 ++++++++++++++++++-- 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/src/Filters/Filter.php b/src/Filters/Filter.php index 76b09eaaf..e2d84f025 100644 --- a/src/Filters/Filter.php +++ b/src/Filters/Filter.php @@ -7,7 +7,8 @@ use Illuminate\Database\Eloquent\Builder; use Illuminate\Http\Request; use Illuminate\Support\Str; -use Orchid\Screen\Field; +use Orchid\Screen\Contracts\Fieldable; +use Orchid\Screen\Repository; abstract class Filter { @@ -40,6 +41,11 @@ public function __construct() $this->request = request(); } + public function query(): iterable + { + return $this->request->only($this->parameters(), []); + } + /** * Apply filter if the request parameters were satisfied. */ @@ -64,7 +70,7 @@ abstract public function run(Builder $builder): Builder; /** * Get the display fields. * - * @return Field[] + * @return Fieldable[] */ public function display(): iterable { @@ -81,7 +87,12 @@ public function name(): string public function render(): string { - return collect($this->display())->reduce(static fn ($html, Field $field) => $html.$field->form('filters')->render()); + $fields = collect($this->display())->map(fn (Fieldable $field) => $field->form('filters')); + $params = $this->query(); + + $builder = new \Orchid\Screen\Builder($fields, new Repository($params)); + + return $builder->generateForm(); } /** diff --git a/tests/Unit/Screen/Layouts/SelectionTest.php b/tests/Unit/Screen/Layouts/SelectionTest.php index d15d4a9b5..d19ed3e7e 100644 --- a/tests/Unit/Screen/Layouts/SelectionTest.php +++ b/tests/Unit/Screen/Layouts/SelectionTest.php @@ -28,11 +28,27 @@ public function testDisplayFilters(): void { $layout = new GroupNameAndEmail; - $html = $layout->build(new Repository); + // Test with empty request + $html = (string) $layout->build(new Repository); collect($layout->filters()) ->map(fn (string $filter) => resolve($filter))->each(function (Filter $filter) use ($html) { - $this->assertStringContainsString($filter->render(), (string) $html); + $this->assertStringContainsString($filter->render(), $html); + }); + + // Test with parameterized request + request()->merge([ + 'name' => 'John Snow', + 'email' => 'john@bastard.com', + ]); + + $htmlParameterized = (string) $layout->build(new Repository); + + collect($layout->filters()) + ->map(fn (string $filter) => resolve($filter))->each(function (Filter $filter) use ($html, $htmlParameterized) { + $render = $filter->render(); + $this->assertStringContainsString($render, $htmlParameterized); + $this->assertStringNotContainsString($render, $html); }); } }