Skip to content

Commit

Permalink
Merge pull request #20 from kgrzelak/dev
Browse files Browse the repository at this point in the history
Required and setAttributes update
  • Loading branch information
kgrzelak authored Jul 1, 2024
2 parents 2e04dc3 + 80cda59 commit 3c73f75
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 4 deletions.
2 changes: 1 addition & 1 deletion src/Attributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
18 changes: 16 additions & 2 deletions src/BaseItem.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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<string, mixed> $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)) {
Expand Down
23 changes: 22 additions & 1 deletion tests/FormInputTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -90,10 +90,31 @@ public function testCanCreateInputWithCustomType(): void
$this->assertEquals('<input type="password" class="form-control">', $item);
}

public function testCanCreateInputWithoutType()
public function testCanCreateInputWithoutType(): void
{
$item = LaravelForm::input()->type(null);

$this->assertEquals('<input class="form-control">', $item);
}

public function testCanCreateInputWithAttributes(): void
{
$item = LaravelForm::input()->setAttributes(['type' => 'password', 'name' => 'password']);

$this->assertEquals('<input type="password" name="password" class="form-control">', $item);
}

public function testCanCreateInputWithRequired(): void
{
$item = LaravelForm::input()->required();

$this->assertEquals('<input type="text" required="required" class="form-control">', $item);
}

public function testCanCreateInputWithoutRequired(): void
{
$item = LaravelForm::input()->required()->required(false);

$this->assertEquals('<input type="text" class="form-control">', $item);
}
}

0 comments on commit 3c73f75

Please sign in to comment.