whitecube / nova-page

Static pages content management for Laravel Nova
https://whitecube.github.io/nova-page
MIT License
238 stars 41 forks source link

KeyValue not supported? #65

Closed Jaspur closed 3 years ago

Jaspur commented 4 years ago

Results in: XrZCFOy4

Padocia commented 3 years ago

the KeyValue field does not convert the result to array. Therefore it's returning a string which cause this issue & since we're not using a model so we can't cast it !

My solution is to extends the KeyValue field & create a new KeyValueJson field to use it instead of the KeyValue field


<?php

namespace App\Nova\Fields;

use Laravel\Nova\Http\Requests\NovaRequest;
use Laravel\Nova\Fields\KeyValue;

class KeyValueJson extends KeyValue
{
    /**
     * Prepare the field element for JSON serialization.
     *
     * @return array
     */
    public function jsonSerialize()
    {
        $parent = parent::jsonSerialize();
        $value = $parent['value'];
        unset($parent['value']);
        return array_merge($parent, [
            'keyLabel' => $this->keyLabel ?? __('Key'),
            'valueLabel' => $this->valueLabel ?? __('Value'),
            'actionText' => $this->actionText ?? __('Add row'),
            'readonlyKeys' => $this->readonlyKeys(app(NovaRequest::class)),
            'canAddRow' => $this->canAddRow,
            'canDeleteRow' => $this->canDeleteRow,
            'value' => is_array($value) ? $value : json_decode($value, true),
        ]);
    }
}
toonvandenbos commented 3 years ago

Hi,

Layout classes have a casts attribute you can add, meaning they can act just as models. I think it is safer to cast the attributes to an array rather than creating an extended KeyValue field, which could cause compatibility issues in the future.

Please take a look at the full docs if you wonder how to create custom layout classes.