Closed Jaspur closed 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),
]);
}
}
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.
Results in:![XrZCFOy4](https://user-images.githubusercontent.com/4254854/83139677-0b918180-a0ed-11ea-97e6-cf938c1f3fd5.png)