Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

KeyValue not supported? #65

Closed
Jaspur opened this issue May 28, 2020 · 2 comments
Closed

KeyValue not supported? #65

Jaspur opened this issue May 28, 2020 · 2 comments

Comments

@Jaspur
Copy link

Jaspur commented May 28, 2020

Results in:
XrZCFOy4

@Padocia
Copy link

Padocia commented Mar 9, 2021

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
Copy link
Member

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants