Skip to content

ENUM fields with forms Select inputs #3023

@grinkevich

Description

@grinkevich

Describe the bug

When you have a proper casting set up in the model with an ENUM field, form fields may experience issues with rendering such fields, even when you pass $options as an array.

For example:
File: resources / views / vendor / platform / fields / select.blade.php : 14
Error: Cannot use object of type App\Enums\EnumType as array

To Reproduce
Steps to reproduce the behaviour:

  1. You have a model with an enum field cast, for example something like that:
    protected $casts = [
        'enabled' => 'boolean',
        'type' => EnumType::class,
        'provider' => EnumProvider::class,
        'rules' => 'array',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];
  1. Plus, you have an options() method that will return a prepared key-label array for select input. That is a sort of workaround to make "options" for the Select input.
    For example:
namespace App\Enums;

enum EnumType: string
{
    case TEXT = 'text';
    case NUMBER = 'number';
    case PRICE = 'price';

    /**
     * Get a label
     */
    public function label(): string
    {
        return match ($this) {
            self::TEXT => __('Text'),
            self::NUMBER => __('Numeric'),
            self::PRICE => __('Price'),
        };
    }

    /**
     * Get all available types as an array
     */
    public static function options(): array
    {
        $options = collect(self::cases())
            ->mapWithKeys(fn($case) => [$case->value => $case->label()])
            ->toArray();

        return $options;
    }
  1. Then you create a select field on the form:
Select::make('enum_type')
    ->required()
    ->title('Enum Type')
    ->empty(__('Select type'))
    ->options(EnumType::options())
    ->help(__('Enum typed options list from the model')),

Expected behaviour
A select element that will have options pre-selected based on the Enum type of field.
P.S. Additionally, the desired behaviour is to pass just the Enum class as options, and it will render options for that.

Server (please complete the following information):

  • Platform Version: 14.52
  • Laravel Version: 12.18
  • PHP Version: 8.4

Metadata

Metadata

Assignees

Labels

DocsMust be added to documentation

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions