Skip to content

Commit

Permalink
feat: add option to customize display name for select based on enums (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
czernika committed Dec 20, 2023
1 parent 18d3463 commit 25a9d04
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/Screen/Fields/Select.php
Original file line number Diff line number Diff line change
Expand Up @@ -91,25 +91,27 @@ public function fromModel($model, string $name, ?string $key = null): self

/**
* @param string $enum
* @param string|null $displayName
*
* @throws \ReflectionException
*
* @return self
*/
public function fromEnum(string $enum): self
public function fromEnum(string $enum, ?string $displayName = null): self
{
$reflection = new \ReflectionEnum($enum);
$options = [];
foreach ($enum::cases() as $item) {
$key = $reflection->isBacked() ? $item->value : $item->name;
$options[$key] = __($item->name);
$options[$key] = is_null($displayName) ? __($item->name) : $item->$displayName();
}
$this->set('options', $options);

return $this->addBeforeRender(function () use ($reflection, $enum) {
$value = [];
collect($this->get('value'))->each(static function ($item) use (&$value, $reflection, $enum) {
if ($item instanceof $enum) {
/** @var \UnitEnum $item */
$value[] = $reflection->isBacked() ? $item->value : $item->name;
} else {
$value[] = $item;
Expand Down
8 changes: 8 additions & 0 deletions tests/App/Enums/RoleNames.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,12 @@ enum RoleNames: string
{
case Admin = 'admin';
case User = 'user';

public function label(): string
{
return match ($this) {
self::Admin => 'Administrator',
self::User => 'Regular user',
};
}
}
13 changes: 13 additions & 0 deletions tests/Unit/Screen/Fields/SelectTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Orchid\Screen\Fields\Select;
use Orchid\Support\Color;
use Orchid\Tests\App\EmptyUserModel;
use Orchid\Tests\App\Enums\RoleNames;
use Orchid\Tests\Unit\Screen\TestFieldsUnitCase;

/**
Expand Down Expand Up @@ -233,6 +234,18 @@ public function testMultiple(): void
$this->assertStringNotContainsString('value="third" selected', $view);
}

public function testFromEnumWithDisplayName(): void
{
$select = Select::make('choice')
->value(RoleNames::User)
->fromEnum(RoleNames::class, 'label');

$view = self::minifyRenderField($select);

// <option value="user" selected>Regular user</option>
$this->assertStringContainsString('value="'.RoleNames::User->value.'" selected>'.RoleNames::User->label(), $view);
}

public function testMultipleFromEnum(): void
{
$select = Select::make('choice')
Expand Down

0 comments on commit 25a9d04

Please sign in to comment.