Power-Components / livewire-powergrid

⚡ PowerGrid generates modern, powerful and easy-to-customize data tables using Laravel Livewire.
https://livewire-powergrid.com
MIT License
1.46k stars 215 forks source link

Column casted as enum #1352

Closed eafarooqi closed 7 months ago

eafarooqi commented 7 months ago

Have you searched through other issues to see if your problem is already reported or has been fixed?

Yes, I did not find it.

Did you read the documentation?

Yes, I did not find it.

Have you tried to publish the views?

Yes - I didn't work.

Is there an error in the console?

No

PHP Version

8.1.0

PowerGrid

5.3.1

Laravel

10.42.0

Livewire

3.4.1

Alpine JS

3.12.0

Theme

Bootstrap

Describe the bug.

I have an enum field which is include in the $cast attribute as enum. As per document i am getting the following error. "Male" is not a valid backing value for enum "App\Enums\Person\Gender"

This only works when cast is removed from the model and column is changed to as follows (as in documentation). But i cannot remove the cast.

return Gender::tryFrom($person->gender)->label();

or as follows

 ->addColumn('gender', function (Person $person) {
                return $person->gender->label();
            });

The error is same as the first one. "Male" is not a valid backing value for enum "App\Enums\Person\Gender"

To Reproduce...

Add enum column to the cast propery in model.

dansysanalyst commented 7 months ago

Hi @eafarooqi,

Following your example, add the column with a different name than gender, for instance gender label.

    public function addColumns(): PowerGridColumns
    {
        return PowerGrid::columns()
            ->addColumn('id')
            ->addColumn('name')
            ->addColumn('gender_label', function (User $person) {
                return $person->gender->label();
            });

Then, when including the column, use the gender_label source:

public function columns(): array
    {
        return [
            Column::make('Id', 'id'),

            Column::make('gender', 'gender_label'),

            //....
        ];
    }

You should be getting the label of your Enum in the table:

CleanShot 2024-01-25 at 20 08 16@2x

eafarooqi commented 7 months ago

Hello @dansysanalyst

thank you so much for the solution. That i have already figured it out that the enum columns can be used with this work around. But is it a bug? or is it a limitation in this package that the enum columns cant be used in the default way ?