From 80cda59bc7a599fdb7df7b9dd6cd8313bde3c0fc Mon Sep 17 00:00:00 2001 From: Krzysztof Grzelak Date: Mon, 1 Jul 2024 19:27:33 +0200 Subject: [PATCH] Required and setAttributes update --- src/Attributes.php | 2 +- src/BaseItem.php | 18 ++++++++++++++++-- tests/FormInputTest.php | 23 ++++++++++++++++++++++- 3 files changed, 39 insertions(+), 4 deletions(-) diff --git a/src/Attributes.php b/src/Attributes.php index e253ced..01f07a8 100644 --- a/src/Attributes.php +++ b/src/Attributes.php @@ -22,7 +22,7 @@ class Attributes */ public function setAttribute(string $name, mixed $value = null): self { - if ($value === null) { + if ($value === null || $value === false) { unset($this->attributes[$name]); return $this; } diff --git a/src/BaseItem.php b/src/BaseItem.php index 24f7c9e..b6411b9 100644 --- a/src/BaseItem.php +++ b/src/BaseItem.php @@ -160,9 +160,9 @@ public function placeholder(string $placeholder): static * @param bool $required * @return static */ - public function required(bool $required): static + public function required(bool $required = true): static { - $this->attributes->setAttribute('required', $required); + $this->attributes->setAttribute('required', $required ? 'required' : null); return $this; } @@ -216,6 +216,20 @@ public function attribute(string|int $name, ?string $value = null): static return $this; } + /** + * @description Set the attributes of the element + * @param array $attributes + * @return static + */ + public function setAttributes(array $attributes): static + { + foreach ($attributes as $name => $value) { + $this->attributes->setAttribute($name, $value); + } + + return $this; + } + public function toHtml(): string { if ($this->hasError() && config('laravel-form.errors.enabled', false)) { diff --git a/tests/FormInputTest.php b/tests/FormInputTest.php index c94a786..286c290 100644 --- a/tests/FormInputTest.php +++ b/tests/FormInputTest.php @@ -90,10 +90,31 @@ public function testCanCreateInputWithCustomType(): void $this->assertEquals('', $item); } - public function testCanCreateInputWithoutType() + public function testCanCreateInputWithoutType(): void { $item = LaravelForm::input()->type(null); $this->assertEquals('', $item); } + + public function testCanCreateInputWithAttributes(): void + { + $item = LaravelForm::input()->setAttributes(['type' => 'password', 'name' => 'password']); + + $this->assertEquals('', $item); + } + + public function testCanCreateInputWithRequired(): void + { + $item = LaravelForm::input()->required(); + + $this->assertEquals('', $item); + } + + public function testCanCreateInputWithoutRequired(): void + { + $item = LaravelForm::input()->required()->required(false); + + $this->assertEquals('', $item); + } }