Skip to content

Commit b2d3e10

Browse files
Refactor form field rule prefix retrieval method
1 parent ad4a0a4 commit b2d3e10

File tree

2 files changed

+21
-9
lines changed

2 files changed

+21
-9
lines changed

resources/views/resources/pages/create/can-validate-create-form-data.blade.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,10 @@
99
->assertHasFormErrors($errors)
1010
->assertNotified();
1111
})->with([
12-
@foreach($getResourceRequiredFormFields() as $key => $field)
12+
@foreach($getResourceFormFieldsByRulePrefix('required') as $key => $field)
1313
'`{{ $key }}` is required' => [['{{ $key }}' => null], ['{{ $key }}' => 'required']],
1414
@endforeach
15-
@foreach($getResourceMaxLengthFormFields() as $key => $field)
16-
'`{{ $key }}` is max {{ $field->getMaxLength() }} characters' => [['{{ $key }}' => Illuminate\Support\Str::random({{ $field->getMaxLength() + 1 }})], ['{{ $key }}' => 'max']],
15+
@foreach($getResourceFormFieldsByRulePrefix('max') as $key => $field)
16+
'`{{ $key }}` is max {{ $getRuleValue($field, 'max') }} characters' => [['{{ $key }}' => Illuminate\Support\Str::random({{ $getRuleValue($field, 'max') + 1 }})], ['{{ $key }}' => 'max']],
1717
@endforeach
1818
]);

src/Concerns/Resources/InteractsWithSchemas.php

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace CodeWithDennis\FilamentTests\Concerns\Resources;
44

5+
use Closure;
56
use Filament\Forms\Components\Field;
67
use Filament\Infolists\Components\Entry;
78
use Filament\Resources\Pages\EditRecord;
@@ -22,18 +23,29 @@ public function getResourceFormFields(): array
2223
return $this->getResourceForm()->getFlatFields(true);
2324
}
2425

25-
public function getResourceRequiredFormFields(): array
26+
public function getResourceFormFieldsByRulePrefix(string $prefix): array
2627
{
2728
return collect($this->getResourceFormFields())
28-
->filter(fn (Field $field): bool => $field->isRequired())
29+
->filter(
30+
fn (Field $field): bool => array_any(
31+
$field->getValidationRules(),
32+
fn (Closure|string $rule): bool => is_string($rule) && str_starts_with($rule, $prefix)
33+
)
34+
)
2935
->all();
3036
}
3137

32-
public function getResourceMaxLengthFormFields(): array
38+
public function getRuleValue(Field $field, string $ruleName): ?string
3339
{
34-
return collect($this->getResourceFormFields())
35-
->filter(fn (Field $field): bool => method_exists($field, 'getMaxLength') && $field->getMaxLength() !== null)
36-
->all();
40+
foreach ($field->getValidationRules() as $rule) {
41+
if (is_string($rule) && str_starts_with($rule, $ruleName.':')) {
42+
[, $value] = explode(':', $rule, 2);
43+
44+
return $value;
45+
}
46+
}
47+
48+
return null;
3749
}
3850

3951
public function getResourceFormFieldKeys(): array

0 commit comments

Comments
 (0)