From 1cbc0d00a1dadcd98ef82f764cf8fec7c93e3cc7 Mon Sep 17 00:00:00 2001 From: Matthew Poulter Date: Sun, 24 Oct 2021 17:31:22 +0200 Subject: [PATCH] Allow nullable field (#40) --- src/Enum.php | 9 ++++++++- src/FlaggedEnum.php | 7 +------ tests/Fields/FieldTest.php | 11 +++++++++++ 3 files changed, 20 insertions(+), 7 deletions(-) diff --git a/src/Enum.php b/src/Enum.php index 3c1ff9a..99e9fd7 100644 --- a/src/Enum.php +++ b/src/Enum.php @@ -36,7 +36,14 @@ function (NovaRequest $request, $model, $attribute, $requestAttribute) { public function attach($class) { return $this->options($class::asSelectArray()) - ->rules('required', new EnumValue($class, false)); + ->rules($this->nullable ? 'nullable' : 'required', new EnumValue($class, false)); + } + + public function nullable($nullable = true, $values = null) + { + $this->rules = str_replace('required', 'nullable', $this->rules); + + return parent::nullable($nullable, $values); } /** diff --git a/src/FlaggedEnum.php b/src/FlaggedEnum.php index fb855a2..76b6e04 100644 --- a/src/FlaggedEnum.php +++ b/src/FlaggedEnum.php @@ -8,12 +8,7 @@ class FlaggedEnum extends BooleanGroup { - public function __construct($name, $attribute = null, $resolveCallback = null) - { - parent::__construct($name, $attribute, $resolveCallback); - - $this->noValueText('None'); - } + public $noValueText = 'None'; public function attach($class) { diff --git a/tests/Fields/FieldTest.php b/tests/Fields/FieldTest.php index 8d180fd..44119fd 100644 --- a/tests/Fields/FieldTest.php +++ b/tests/Fields/FieldTest.php @@ -3,6 +3,7 @@ namespace SimpleSquid\Nova\Fields\Enum\Tests\Fields; use BenSampo\Enum\Rules\EnumValue; +use Laravel\Nova\Http\Requests\NovaRequest; use SimpleSquid\Nova\Fields\Enum\Enum; use SimpleSquid\Nova\Fields\Enum\Tests\Examples\IntegerEnum; use SimpleSquid\Nova\Fields\Enum\Tests\TestCase; @@ -56,4 +57,14 @@ public function it_displays_enum_options() ], $this->field->meta['options']); } } + + /** @test */ + public function it_can_be_nullable() + { + $this->field->nullable(); + + $this->assertNotContains('required', $this->field->rules); + $this->assertContains('nullable', $this->field->rules); + $this->assertFalse($this->field->isRequired(new NovaRequest())); + } }