Skip to content

Commit

Permalink
Feature/filters autofill (#2895)
Browse files Browse the repository at this point in the history
* Allow to pass to display() not only Field`s but also Group`s

* Add Autofill trait for Filter

* Add test
  • Loading branch information
Mystical0628 authored Sep 12, 2024
1 parent 26b9f8e commit 32f800e
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 5 deletions.
17 changes: 14 additions & 3 deletions src/Filters/Filter.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down Expand Up @@ -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.
*/
Expand All @@ -64,7 +70,7 @@ abstract public function run(Builder $builder): Builder;
/**
* Get the display fields.
*
* @return Field[]
* @return Fieldable[]
*/
public function display(): iterable
{
Expand All @@ -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();
}

/**
Expand Down
20 changes: 18 additions & 2 deletions tests/Unit/Screen/Layouts/SelectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
}
}

0 comments on commit 32f800e

Please sign in to comment.