simplesquid / nova-enum-field

An enum field and filters for Laravel Nova.
MIT License
52 stars 26 forks source link

Nova Enum does not persist value on edit form #55

Closed kingsloi closed 7 months ago

kingsloi commented 7 months ago

Given model

Models/Inventory.php

protected $casts = [
'type' => InventoryType::class,
];

Given enum

Enums/InventoryType.php

final class InventoryType extends Enum
{
const UNAVAILABLE = 0;
const RENTAL = 1;
const FOR_SALE = 2;
const AVAILABLE = 3;
const SOLD = 4;
}

Given Nova Resource

Nova/Inventory.php

Enum::make('Type')->attach(InventoryType::class),

In Nova, when setting value for type, it saves correctly, and on the index & detail view it displays correctly, but when on the edit form, it fails to pre-select the already chosen value, leading to upon saving, it saving a NULL value, causing a validation error, unless ->nullable() is added, but then overrides the previously selected value with NULL

2024-02-08 19 41 02

kingsloi commented 7 months ago

Discovered it was due to accessor

public function getTypeAttribute($value)
{
    return InventoryType::getKey($value ?? 0);
}

removing it (and instead making use of enum description) fixed it