valentin-morice / filament-json-column

A simple package to view and edit your JSON columns in Filament
MIT License
32 stars 6 forks source link

JSON stored incorrectly #3

Closed wq9578 closed 5 months ago

wq9578 commented 5 months ago

When saving a record, the JSON data is stored incorrectly. Instead of the array data an array containing the serialized JSON string (with key "0") is stored.

This is due to a bug in this line: https://github.com/valentin-morice/filament-json-column/blob/b25b146c090d73adeac78a583f47dc8eabcf2894/src/FilamentJsonColumn.php#L27

The context is:

        $this->afterStateHydrated(static function (FilamentJsonColumn $component, $state): void {
            if(is_array($state)) {
                $state = json_encode($state);
            }

            $component->state((array) $state);
        });

Instead of

            $component->state((array) $state);

it must be

            $component->state(state);

(removing the conversion via (array)).

Since $state is a string (a result of json_encode()), a conversion with (array) produces an array with the string as the single element (with key "0").

wq9578 commented 5 months ago

It still creates problems, even after the change (displayed correctly, but stored as a plain string in the JSON column).

I now use the following workaround:

            FilamentJsonColumn::make('json')->viewerOnly()->columnSpanFull()
                ->dehydrated(false), // prevent JSON corruption

See: https://filamentphp.com/docs/3.x/forms/advanced#preventing-a-field-from-being-dehydrated

valentin-morice commented 5 months ago

Thanks for opening this issue. Encoding the state to JSON before dehydrating it looks like it's solving the problem:

$this->beforeStateDehydrated(function(FilamentJsonColumn $component, $state) {
            $component->state(json_decode($state));
        });

What do you think? If it doesn't cause any further bugs, I'll push the fix now.

EDIT: Had to solve additional issues due to the sequence of JSON parsing throughout the plugin, from PHP to Alpine.

valentin-morice commented 5 months ago

Solved by fe0065d.