Skip to content

Commit

Permalink
Support simple array options in x-select (#89)
Browse files Browse the repository at this point in the history
  • Loading branch information
rawilk authored Mar 21, 2023
1 parent 7bf0e42 commit 6c53c53
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 13 deletions.
39 changes: 26 additions & 13 deletions src/Components/Inputs/Select.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace Rawilk\FormComponents\Components\Inputs;

use function config;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\HtmlString;
Expand Down Expand Up @@ -62,18 +62,7 @@ public function __construct(
$this->disabledField = $disabledField ?? config('form-components.defaults.global.disabled_field', 'disabled');
$this->childrenField = $childrenField ?? config('form-components.defaults.global.children_field', 'children');

$this->options = collect($options)
->map(function ($value, $key) {
// If the key is not numeric, we're going to assume this is the value.
if (! is_numeric($key)) {
return [
$this->valueField => $key,
$this->labelField => $value,
];
}

return $value;
})->values();
$this->options = $this->normalizeOptions($options);
}

/**
Expand All @@ -99,4 +88,28 @@ public function inputClass(): string
'input-error' => $this->hasErrorsAndShow($this->name),
]);
}

protected function normalizeOptions(array|Collection $options): Collection
{
return collect($options)
->map(function ($value, $key) {
// If the key is not numeric, we're going to assume this is the value.
if (! is_numeric($key)) {
return [
$this->valueField => $key,
$this->labelField => $value,
];
}

// If the value is a simple value, we need to convert it to an array.
if (! is_iterable($value) && ! $value instanceof Model) {
return [
$this->valueField => $value,
$this->labelField => $value,
];
}

return $value;
});
}
}
31 changes: 31 additions & 0 deletions tests/Components/Inputs/SelectTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -307,3 +307,34 @@
})
->assertSeeInOrder(['Germany', 'Canada', 'United States', 'France']);
});

test('simple array options are supported', function () {
$options = [
'option_1',
'option_2',
];

$template = <<<'HTML'
<form>
<x-select name="my_options" :options="$options" />
</form>
HTML;

Route::get('/test', fn () => Blade::render($template, ['options' => $options]));

get('/test')
->assertFormExists('form', function (AssertForm $form) {
$form->findSelect('select', function (AssertSelect $select) {
$select->containsOptions(
[
'value' => 'option_1',
'text' => 'option_1',
],
[
'value' => 'option_2',
'text' => 'option_2',
],
);
});
});
});

0 comments on commit 6c53c53

Please sign in to comment.