diff --git a/en/fields/json.md b/en/fields/json.md index e2e930e3..d83daa01 100644 --- a/en/fields/json.md +++ b/en/fields/json.md @@ -2,150 +2,244 @@ - [Basics](#basics) - [Field Set](#fields) +- [Vertical Mode](#vertical) - [Key/Value Mode](#key-value) - [Only Value Mode](#only-value) -- [Object Mode](#object-mode) +- [Object Mode](#object) - [Nested Json](#nested) -- [Default Value](#default) -- [Filtering Empty](#filtering-empty) -- [Creatable/Removable](#creatable-removable) -- [Vertical Mode](#vertical) -- [Sorting with dragging](#reorderable) -- [Applying in Filters](#filter) +- [Table Preview](#table-preview) +- [Adding/Removing](#creatable-removable) - [Buttons](#buttons) - [Modifiers](#modify) +- [Drag-and-Drop Sorting](#reorderable) +- [Empty Message](#empty-message) +- [Using in Filters](#filter) +- [Filtering "Empty" Values](#filter-empty) +- [Default Value](#default) +- [Blade Usage](#blade-usage) --- + ## Basics Contains all [Basic methods](/docs/{{version}}/fields/basic-methods). -The `Json` field is designed for convenient work with the json data type. -In most cases, it is used with arrays of objects via `TableBuilder`, but it also supports a mode for working with a single object. +The `Json` field is designed for columns that store an array of objects. +The object schema is defined with the `fields()` method, and each UI row corresponds to one object in the array. @include('_includes/note-about-multiple-cast') + ## Field Set -Assume that the structure of your json looks like this: +The `fields()` method defines the fields that will be displayed in each `Json` row. -```json -[{"title": "title", "value": "value", "active": true}] +```php +fields(FieldsContract|Closure|iterable $fields, string $orientation = 'horizontal') ``` -This is a set of objects with fields "title", "value" and "active". -To specify such a set of fields, the `fields()` method is used. +- `$fields` - a set of fields. +- `$orientation` - field layout inside the row: `horizontal` or `vertical`. + +Example: ```php -fields(FieldsContract|Closure|iterable $fields) +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:3] +use MoonShine\UI\Fields\Json; +use MoonShine\UI\Fields\Text; + +Json::make('Product Options', 'options') + ->fields([ + Text::make('Title'), + Text::make('Value'), + ]) ``` -Example: +For the field above, data is stored as an array of objects: + +```json +[ + { + "title": "Title 1", + "value": "Value 1" + }, + { + "title": "Title 2", + "value": "Value 2" + } +] +``` + + + +## Vertical Mode + +Vertical mode changes the layout of fields inside each `Json` row: fields are displayed one below another instead of in one line. +This is useful for long values, Textarea, Select with many options, and nested components. ```php // torchlight! {"summaryCollapsedIndicator": "namespaces"} -// [tl! collapse:4] +// [tl! collapse:3] use MoonShine\UI\Fields\Json; -use MoonShine\UI\Fields\Position; -use MoonShine\UI\Fields\Switcher; use MoonShine\UI\Fields\Text; Json::make('Product Options', 'options') ->fields([ - Position::make(), Text::make('Title'), Text::make('Value'), - Switcher::make('Active'), + ], orientation: 'vertical') +``` + +You can also use the `vertical()` method: + +```php +vertical(bool $condition = true) +``` + +When called without arguments, the method enables vertical mode. If `false` is passed, the field returns to horizontal layout. + +```php +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:2] +use MoonShine\UI\Fields\Json; + +Json::make('Product Options', 'options') + ->fields([ + Text::make('Title'), + Text::make('Value'), ]) + ->vertical() ``` -@preview('fields.json') +```php +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:2] +use MoonShine\UI\Fields\Json; + +Json::make('Product Options', 'options') + ->fields([ + Text::make('Title'), + Text::make('Value'), + ], orientation: 'vertical') + ->vertical(false) +``` + ## Key/Value Mode -When your data has a key/value structure, like in the following example `{"key": "value"}`, the `keyValue()` method is used. +The `keyValue()` method is used for JSON objects where the key is stored as a property name and the value is stored as that property's value. ```php keyValue( - string $key = 'Key', - string $value = 'Value', + string|FieldContract $key = 'Key', + string|FieldContract $value = 'Value', ?FieldContract $keyField = null, ?FieldContract $valueField = null, + string $orientation = 'horizontal', ) ``` -- `$key` — the label for the "key" field, -- `$value` — the label for the "value" field, -- `$keyField` — the option to replace the "key" field with your own (default is `Text`), -- `$valueField` — the option to replace the "value" field with your own (default is `Text`). - -Example: +By default, text fields are created for the key and value: ```php -Json::make('Data') +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:2] +use MoonShine\UI\Fields\Json; + +Json::make('Contacts', 'contacts') ->keyValue() ``` -![json_key_value](https://raw.githubusercontent.com/moonshine-software/doc/4.x/resources/screenshots/json_key_value.png#light) -![json_key_value_dark](https://raw.githubusercontent.com/moonshine-software/doc/4.x/resources/screenshots/json_key_value_dark.png#dark) - -Example with changing field types: +If you need to replace the key or value fields, pass your own fields: ```php // torchlight! {"summaryCollapsedIndicator": "namespaces"} -// [tl! collapse:3] +// [tl! collapse:4] use MoonShine\UI\Fields\Json; use MoonShine\UI\Fields\Select; use MoonShine\UI\Fields\Text; -Json::make('Label', 'data') +Json::make('Contacts', 'contacts') ->keyValue( keyField: Select::make('Key') - ->options(['vk' => 'VK', 'email' => 'E-mail']), + ->options([ + 'vk' => 'VK', + 'email' => 'E-mail', + ]), valueField: Text::make('Value'), ) ``` + ## Only Value Mode -If you need to store only values, like in the example `["value_1", "value_2"]`, the `onlyValue()` method is used. +The `onlyValue()` method is used for JSON arrays where each row is stored as a separate value without an object. ```php -onlyValue( - string $value = 'Value', - ?FieldContract $valueField = null, -) +onlyValue(string $value = 'Value', ?FieldContract $valueField = null) ``` -- `$value` - the label for the "value" field, -- `$valueField` - the option to replace the "value" field with your own (default is `Text`). +- `$value` - the field label. Used for the default `Text` field. +- `$valueField` - the value field, if you need to replace `Text` with another field. Example: ```php -Json::make('Data') +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:2] +use MoonShine\UI\Fields\Json; + +Json::make('Tags', 'tags') ->onlyValue() ``` -![json_only_value](https://raw.githubusercontent.com/moonshine-software/doc/4.x/resources/screenshots/json_only_value.png#light) -![json_only_value_dark](https://raw.githubusercontent.com/moonshine-software/doc/4.x/resources/screenshots/json_only_value_dark.png#dark) +Data will be stored as a JSON array of values: - -## Object Mode +```json +[ + "lorem", + "ipsum" +] +``` -In most cases, the `Json` field works with an array of objects via `TableBuilder`. -However, it is also possible to work with an object, for example, `{"title": "Title", "active": false}`. -For this, the `object()` method is used. +If you need to replace the value field, pass `$valueField`: -Example: +```php +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:3] +use MoonShine\UI\Fields\Json; +use MoonShine\UI\Fields\Select; + +Json::make('Contacts', 'contacts') + ->onlyValue( + valueField: Select::make('Type') + ->options([ + 'vk' => 'VK', + 'email' => 'E-mail', + ]), + ) +``` + + + +## Object Mode + +By default, `Json` works with an array of objects. The `object()` method is used when the column should store a single JSON object, for example `{"title": "Title", "active": false}`. ```php -Json::make('Product Options', 'options') +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:4] +use MoonShine\UI\Fields\Json; +use MoonShine\UI\Fields\Switcher; +use MoonShine\UI\Fields\Text; + +Json::make('Settings', 'settings') ->fields([ Text::make('Title'), Switcher::make('Active'), @@ -153,14 +247,21 @@ Json::make('Product Options', 'options') ->object() ``` +When `object()` is used, rows cannot be added or removed. The UI displays only the values defined through `fields()`. + -## Nested Json -To create more complex structures, you may need to use the nested fields `Json` and **MoonShine** this allows. +## Nested Json -Example: +You can use another `Json` field inside `Json` when you need to describe a more complex data structure. ```php +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:4] +use MoonShine\UI\Fields\Json; +use MoonShine\UI\Fields\Number; +use MoonShine\UI\Fields\Text; + Json::make('Products', 'products') ->fields([ Text::make('Name', 'name'), @@ -173,7 +274,7 @@ Json::make('Products', 'products') ]) ``` -Result: +Data will be stored with a nested object: ```json [ @@ -187,103 +288,101 @@ Result: ] ``` - -## Default Value + + +## Table Preview -As in other fields, there is an option to specify a default value using the `default()` method. -In this case, an array must be provided. +By default, the `Json` field preview is displayed as a read-only list where each field label is shown next to its value. +The `table()` method switches the field to `preview` mode and displays the value as a read-only table. ```php -default(mixed $default) +table(bool $condition = true) ``` Example: ```php -Json::make('Data') - ->keyValue('Key', 'Value') - ->default([ - [ - 'key' => 'Default key', - 'value' => 'Default value', - ] - ]), +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:3] +use MoonShine\UI\Fields\Json; +use MoonShine\UI\Fields\Text; -Json::make('Product Options', 'options') +Json::make('Products', 'products') ->fields([ - Text::make('Title'), - Text::make('Value'), - Switcher::make('Active'), - ]) - ->default([ - [ - 'title' => 'Default title', - 'value' => 'Default value', - 'active' => true, - ] - ]), - -Json::make('Values') - ->onlyValue() - ->default([ - ['value' => 'Default value'] + Text::make('Name'), + Json::make('Links') + ->fields([ + Text::make('Label'), + Text::make('Url'), + ]), ]) + ->table() ``` - -## Filtering Empty +The field will be displayed as a table where `Name` and `Links` are table headers. -By default, `Json` field filters all empty values, but this behavior can be disabled. +You can also enable table preview only for a nested `Json` field: ```php -Json::make('data')->stopFilteringEmpty() +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:3] +use MoonShine\UI\Fields\Json; +use MoonShine\UI\Fields\Text; + +Json::make('Products', 'products') + ->fields([ + Text::make('Name'), + Json::make('Links') + ->fields([ + Text::make('Label'), + Text::make('Url'), + ]) + ->table(), + ]) ``` -## Creatable/Removable -By default, the `Json` field contains only one element. -The `creatable()` method allows adding new elements, while `removable()` enables their removal. +## Adding/Removing + +Rows can be added and removed by default. +The `creatable()` method controls adding new rows, and `removable()` controls removing existing rows. ```php creatable( Closure|bool|null $condition = null, ?int $limit = null, ?ActionButtonContract $button = null, + bool $hideButton = false, ) ``` -- `$condition` - condition under which the method should be applied, -- `$limit` - limit on the number of possible elements, -- `$button` - option to replace the add button with your own. +- `$condition` - the condition under which adding rows is available. +- `$limit` - the maximum number of rows. +- `$button` - a custom add button. +- `$hideButton` - hides the add button without disabling the ability to add rows at the field level. -```php -removable( - Closure|bool|null $condition = null, - array $attributes = [], -) -``` - -- `$condition` - condition under which the method should be applied, -- `$attributes` - HTML attributes for the remove button. - -Example: +If `$limit` is specified, the add button remains visible but becomes disabled when the limit is reached. ```php -Json::make('Data') - ->keyValue() +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:3] +use MoonShine\UI\Fields\Json; +use MoonShine\UI\Fields\Text; + +Json::make('Product Options', 'options') + ->fields([ + Text::make('Title'), + Text::make('Value'), + ]) ->creatable(limit: 6) - ->removable() ``` -![json_removable](https://raw.githubusercontent.com/moonshine-software/doc/4.x/resources/screenshots/json_removable.png#light) -![json_removable_dark](https://raw.githubusercontent.com/moonshine-software/doc/4.x/resources/screenshots/json_removable_dark.png#dark) - -### Customizing the Add Button +Customizing the add button: ```php // torchlight! {"summaryCollapsedIndicator": "namespaces"} -// [tl! collapse:2] +// [tl! collapse:3] use MoonShine\UI\Components\ActionButton; use MoonShine\UI\Fields\Json; @@ -294,66 +393,69 @@ Json::make('Data') ) ``` -### HTML Attributes for the Remove Button +Hiding the add button: ```php -Json::make('Data', 'data.content') +Json::make('Data') ->fields([ Text::make('Title'), - Image::make('Image'), Text::make('Value'), ]) - ->removable(attributes: ['@click.prevent' => 'customAsyncRemove']) - ->creatable() + ->creatable(hideButton: true) ``` - -## Vertical Mode - -The `vertical()` method allows changing the display of the table from horizontal mode to vertical. - -Example: +The `removable()` method controls displaying the row remove button. ```php -Json::make('Data') - ->vertical() +removable( + Closure|bool|null $condition = null, + array $attributes = [], +) ``` -![json_vertical](https://raw.githubusercontent.com/moonshine-software/doc/4.x/resources/screenshots/json_vertical.png#light) -![json_vertical_dark](https://raw.githubusercontent.com/moonshine-software/doc/4.x/resources/screenshots/json_vertical_dark.png#dark) - - -## Drag-and-Drop Sorting +- `$condition` - the condition under which removing rows is available. +- `$attributes` - HTML attributes for the remove button. -Allows you to drag and drop rows to change their sorting order. -This mode is enabled by default. To disable it, call the `reorderable(false)` method: +With `removable(false)`, users can add new rows but cannot remove existing rows. ```php -->reorderable(false) -``` - -> [!NOTE] -> If you need to specify a custom handler (endpoint), use the `modifyTable` method and set `reorderable($url)` via the `TableBuilder`. +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:3] +use MoonShine\UI\Fields\Json; +use MoonShine\UI\Fields\Text; - -## Application in Filters +Json::make('Product Options', 'options') + ->fields([ + Text::make('Title'), + Text::make('Value'), + ]) + ->removable(false) +``` -If the field is used in filters, the filtering mode must be enabled using the `filterMode()` method. -This method adapts the field's behavior for filtering and disables the ability to add new elements. +HTML attributes for the remove button: ```php -Json::make('Data') +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:4] +use MoonShine\UI\Fields\Image; +use MoonShine\UI\Fields\Json; +use MoonShine\UI\Fields\Text; + +Json::make('Data', 'data.content') ->fields([ - Text::make('Title', 'title'), - Text::make('Value', 'value') + Text::make('Title'), + Image::make('Image'), + Text::make('Value'), ]) - ->filterMode() + ->removable(attributes: ['@click.prevent' => 'customAsyncRemove']) + ->creatable() ``` + ## Buttons -The `buttons()` method allows overriding the buttons used in the field. +The `buttons()` method allows you to override the buttons used in field rows. By default, only the remove button is available. ```php @@ -363,6 +465,13 @@ buttons(array $buttons) Example: ```php +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:5] +use MoonShine\UI\Components\ActionButton; +use MoonShine\UI\Fields\Image; +use MoonShine\UI\Fields\Json; +use MoonShine\UI\Fields\Text; + Json::make('Data', 'data.content') ->fields([ Text::make('Title'), @@ -374,75 +483,80 @@ Json::make('Data', 'data.content') ->icon('trash') ->onClick(fn() => 'remove()', 'prevent') ->secondary() - ->showInLine() + ->showInLine(), ]) ``` + ## Modifiers -The `Json` field provides the ability to modify buttons or the table in "preview" or "default" modes, instead of completely replacing them. +The `Json` field allows you to modify buttons in `preview` or `default` modes without replacing them completely. +For table preview, a table modifier is also available. -### Remove Button Modifier +### Add Button Modifier -The `modifyRemoveButton()` method allows changing the remove button. +The `modifyCreateButton()` method allows you to modify the add button. ```php /** - * @param Closure(ActionButton $button, self $field): ActionButton $callback + * @param Closure(ActionButton $button, self $field): ActionButton $callback */ -modifyRemoveButton(Closure $callback) +modifyCreateButton(Closure $callback) ``` Example: ```php // torchlight! {"summaryCollapsedIndicator": "namespaces"} -// [tl! collapse:2] +// [tl! collapse:3] use MoonShine\UI\Components\ActionButton; use MoonShine\UI\Fields\Json; Json::make('Data') - ->modifyRemoveButton( - fn(ActionButton $button) => $button->customAttributes([ - 'class' => 'btn-secondary' + ->creatable() + ->modifyCreateButton( + fn(ActionButton $button): ActionButton => $button->customAttributes([ + 'class' => 'btn-primary', ]) ) ``` -### Create Button Modifier +### Remove Button Modifier -The `modifyCreateButton()` method allows changing the create button. +The `modifyRemoveButton()` method allows you to modify the remove button. ```php /** - * @param Closure(ActionButton $button, self $field): ActionButton $callback + * @param Closure(ActionButton $button, self $field): ActionButton $callback */ -modifyCreateButton(Closure $callback) +modifyRemoveButton(Closure $callback) ``` +Example: + ```php // torchlight! {"summaryCollapsedIndicator": "namespaces"} -// [tl! collapse:2] +// [tl! collapse:3] use MoonShine\UI\Components\ActionButton; use MoonShine\UI\Fields\Json; Json::make('Data') - ->creatable() - ->modifyCreateButton( - fn(ActionButton $button) => $button->customAttributes([ - 'class' => 'btn-primary' + ->modifyRemoveButton( + fn(ActionButton $button): ActionButton => $button->customAttributes([ + 'class' => 'btn-secondary', ]) ) ``` ### Table Modifier -The `modifyTable()` method allows modifying the table (`TableBuilder`) for all visual modes of the field. +The `modifyTable()` method allows you to modify the `TableBuilder` table when the `Json` field is displayed in preview mode. +The method is applied only for table preview, meaning when the field is rendered through `preview()` or `previewMode()` and the `table()` method is enabled. ```php /** - * @param Closure(TableBuilder $table, bool $preview): TableBuilder $callback + * @param Closure(TableBuilder $table, bool $preview): TableBuilder $callback */ modifyTable(Closure $callback) ``` @@ -451,14 +565,275 @@ Example: ```php // torchlight! {"summaryCollapsedIndicator": "namespaces"} -// [tl! collapse:2] +// [tl! collapse:3] use MoonShine\UI\Components\Table\TableBuilder; use MoonShine\UI\Fields\Json; Json::make('Data') + ->table() ->modifyTable( - fn(TableBuilder $table, bool $preview) => $table->customAttributes([ - 'style' => 'width: 50%;' + fn(TableBuilder $table, bool $preview): TableBuilder => $table->customAttributes([ + 'style' => 'width: 20%;', ]) ) ``` + +You can also use compatible `TableBuilder` settings supported by the current table template: + +```php +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:3] +use MoonShine\UI\Components\Table\TableBuilder; +use MoonShine\UI\Fields\Json; + +Json::make('Data') + ->table() + ->modifyTable( + fn(TableBuilder $table): TableBuilder => $table + ->simple() + ->sticky() + ) +``` + +`trAttributes()` and `tdAttributes()` are available for rows and cells: + +```php +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:3] +use MoonShine\UI\Components\Table\TableBuilder; +use MoonShine\UI\Fields\Json; + +Json::make('Data') + ->table() + ->modifyTable( + fn(TableBuilder $table): TableBuilder => $table + ->trAttributes(fn(): array => ['style' => 'background: red']) + ->tdAttributes(fn(): array => ['style' => 'background: blue']) + ) +``` + + + +## Drag-and-Drop Sorting + +Drag-and-drop row sorting is disabled by default. + +The `reorderable()` method controls displaying the row drag handle. + +```php +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:3] +use MoonShine\UI\Fields\Json; +use MoonShine\UI\Fields\Text; + +Json::make('Product Options', 'options') + ->fields([ + Text::make('Title'), + Text::make('Value'), + ]) + ->reorderable() +``` + +To explicitly disable drag-and-drop sorting, pass `false`: + +```php +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:3] +use MoonShine\UI\Fields\Json; +use MoonShine\UI\Fields\Text; + +Json::make('Product Options', 'options') + ->fields([ + Text::make('Title'), + Text::make('Value'), + ]) + ->reorderable(false) +``` + + + +## Empty Message + +When the `Json` field has no rows, an empty block is displayed in the interface. +The `emptyMessage()` method controls the text inside this block. + +```php +emptyMessage(string $message) +``` + +Example: + +```php +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:3] +use MoonShine\UI\Fields\Json; +use MoonShine\UI\Fields\Text; + +Json::make('Product Options', 'options') + ->fields([ + Text::make('Title'), + Text::make('Value'), + ]) + ->emptyMessage('No options added') +``` + +Nested `Json` fields can have a separate message: + +```php +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:3] +use MoonShine\UI\Fields\Json; +use MoonShine\UI\Fields\Text; + +Json::make('Products', 'products') + ->fields([ + Text::make('Name'), + Json::make('Links') + ->fields([ + Text::make('Label'), + Text::make('Url'), + ]) + ->emptyMessage('No links added'), + ]) +``` + + + +## Using in Filters + +If the field is used in filters, enable filter mode with the `filterMode()` method. +It adapts the field behavior for filters and disables adding new rows. + +```php +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:3] +use MoonShine\UI\Fields\Json; +use MoonShine\UI\Fields\Text; + +Json::make('Data') + ->fields([ + Text::make('Title', 'title'), + Text::make('Value', 'value'), + ]) + ->filterMode() +``` + +For nested `Json`, filter mode is set separately: + +```php +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:3] +use MoonShine\UI\Fields\Json; +use MoonShine\UI\Fields\Text; + +Json::make('Data') + ->fields([ + Text::make('Title', 'title'), + Json::make('Links', 'links') + ->fields([ + Text::make('Label', 'label'), + Text::make('Url', 'url'), + ]) + ->filterMode(), + ]) +``` + + + +## Filtering "Empty" Values + +By default, the `Json` field filters all empty values, but this behavior can be disabled. + +```php +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:2] +use MoonShine\UI\Fields\Json; + +Json::make('Data', 'data') + ->stopFilteringEmpty() +``` + + + +## Default Value + +As with other fields, the default value is set with the `default()` method. +For `Json`, pass an array of objects. + +```php +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:3] +use MoonShine\UI\Fields\Json; +use MoonShine\UI\Fields\Text; + +Json::make('Product Options', 'options') + ->fields([ + Text::make('Title'), + Text::make('Value'), + ]) + ->default([ + [ + 'title' => 'Default title', + 'value' => 'Default value', + ], + ]) +``` + + + +## Blade Usage + +The field component can be used directly in Blade templates: + +```bladehtml + +``` + +Available attributes: + +```bladehtml + +``` diff --git a/ru/fields/json.md b/ru/fields/json.md index ded878cd..44743013 100644 --- a/ru/fields/json.md +++ b/ru/fields/json.md @@ -2,150 +2,244 @@ - [Основы](#basics) - [Набор полей](#fields) -- [Режим "Ключ/Значение"](#key-value) -- [Режим "Только значения"](#only-value) -- [Режим "Объект"](#object-mode) +- [Вертикальный режим](#vertical) +- [Режим "Ключ/значение"](#key-value) +- [Режим "Только значение"](#only-value) +- [Режим "Объект"](#object) - [Вложенные Json](#nested) -- [Значение по умолчанию](#default) -- [Фильтрация "пустых" значений](#filtering-empty) +- [Табличный preview](#table-preview) - [Добавление/Удаление](#creatable-removable) -- [Вертикальный режим](#vertical) -- [Сортировка перетаскиванием](#reorderable) -- [Применение в фильтрах](#filter) - [Кнопки](#buttons) - [Модификаторы](#modify) +- [Сортировка перетаскиванием](#reorderable) +- [Сообщение при отсутствии элементов](#empty-message) +- [Применение в фильтрах](#filter) +- [Фильтрация "пустых" значений](#filter-empty) +- [Значение по умолчанию](#default) +- [Использование в blade](#blade-usage) --- + ## Основы Содержит все [Базовые методы](/docs/{{version}}/fields/basic-methods). -Поле `Json` предназначено для удобной работы с типом данных json. -В большинстве случаев оно используется с массивами объектов через `TableBuilder`, но также поддерживает режим работы с одним объектом. +Поле `Json` предназначено для работы с колонками, в которых хранится массив объектов. +Схема объекта задается через метод `fields()`, а каждая строка интерфейса соответствует одному объекту массива. @include('_includes/note-about-multiple-cast') + ## Набор полей -Предположим, что структура вашего json имеет следующий вид: +Метод `fields()` задает поля, которые будут отображаться в каждой строке `Json`. -```json -[{"title": "title", "value": "value", "active": true}] +```php +fields(FieldsContract|Closure|iterable $fields, string $orientation = 'horizontal') ``` -Это набор объектов с полями "title", "value" и "active". -Чтобы указать такой набор полей, используется метод `fields()`. +- `$fields` - набор полей. +- `$orientation` - расположение полей в строке: `horizontal` или `vertical`. + +Пример: ```php -fields(FieldsContract|Closure|iterable $fields) +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:3] +use MoonShine\UI\Fields\Json; +use MoonShine\UI\Fields\Text; + +Json::make('Product Options', 'options') + ->fields([ + Text::make('Title'), + Text::make('Value'), + ]) ``` -Пример: +Для поля выше данные хранятся как массив объектов: + +```json +[ + { + "title": "Title 1", + "value": "Value 1" + }, + { + "title": "Title 2", + "value": "Value 2" + } +] +``` + + + +## Вертикальный режим + +Вертикальный режим меняет расположение полей внутри каждой строки `Json`: поля выводятся друг под другом, а не в одну линию. +Это удобно для длинных значений, Textarea, Select с большим количеством опций и вложенных компонентов. ```php // torchlight! {"summaryCollapsedIndicator": "namespaces"} -// [tl! collapse:4] +// [tl! collapse:3] use MoonShine\UI\Fields\Json; -use MoonShine\UI\Fields\Position; -use MoonShine\UI\Fields\Switcher; use MoonShine\UI\Fields\Text; Json::make('Product Options', 'options') ->fields([ - Position::make(), Text::make('Title'), Text::make('Value'), - Switcher::make('Active'), + ], orientation: 'vertical') +``` + +Также можно использовать метод `vertical()`: + +```php +vertical(bool $condition = true) +``` + +При вызове без аргументов метод включает вертикальный режим. Если передать `false`, поле вернется к горизонтальному расположению. + +```php +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:2] +use MoonShine\UI\Fields\Json; + +Json::make('Product Options', 'options') + ->fields([ + Text::make('Title'), + Text::make('Value'), ]) + ->vertical() ``` -@preview('fields.json') +```php +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:2] +use MoonShine\UI\Fields\Json; + +Json::make('Product Options', 'options') + ->fields([ + Text::make('Title'), + Text::make('Value'), + ], orientation: 'vertical') + ->vertical(false) +``` -## Режим "Ключ/Значение" -Когда ваши данные имеют структуру ключ/значение, как в следующем примере `{"key": "value"}`, используется метод `keyValue()`. +## Режим "Ключ/значение" + +Метод `keyValue()` используется для JSON-объектов, где ключ хранится как имя свойства, а значение - как значение этого свойства. ```php keyValue( - string $key = 'Key', - string $value = 'Value', + string|FieldContract $key = 'Key', + string|FieldContract $value = 'Value', ?FieldContract $keyField = null, ?FieldContract $valueField = null, + string $orientation = 'horizontal', ) ``` -- `$key` — заголовок поля "ключ", -- `$value` — заголовок поля "значение", -- `$keyField` — возможность заменить поле "ключ" на своё (по умолчанию — `Text`), -- `$valueField` — возможность заменить поле "значение" на своё (по умолчанию — `Text`). - -Пример: +По умолчанию для ключа и значения будут созданы текстовые поля: ```php -Json::make('Data') +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:2] +use MoonShine\UI\Fields\Json; + +Json::make('Contacts', 'contacts') ->keyValue() ``` -![json_key_value](https://raw.githubusercontent.com/moonshine-software/doc/4.x/resources/screenshots/json_key_value.png#light) -![json_key_value_dark](https://raw.githubusercontent.com/moonshine-software/doc/4.x/resources/screenshots/json_key_value_dark.png#dark) - -Пример с изменением типов полей: +Если нужно заменить поля ключа или значения, передайте свои поля: ```php // torchlight! {"summaryCollapsedIndicator": "namespaces"} -// [tl! collapse:3] +// [tl! collapse:4] use MoonShine\UI\Fields\Json; use MoonShine\UI\Fields\Select; use MoonShine\UI\Fields\Text; -Json::make('Label', 'data') +Json::make('Contacts', 'contacts') ->keyValue( keyField: Select::make('Key') - ->options(['vk' => 'VK', 'email' => 'E-mail']), + ->options([ + 'vk' => 'VK', + 'email' => 'E-mail', + ]), valueField: Text::make('Value'), ) ``` -## Режим "Только значения" -Если необходимо хранить только значения, как в примере `["value_1", "value_2"]`, используется метод `onlyValue()`. +## Режим "Только значение" + +Метод `onlyValue()` используется для JSON-массивов, где каждая строка хранится как отдельное значение без объекта. ```php -onlyValue( - string $value = 'Value', - ?FieldContract $valueField = null, -) +onlyValue(string $value = 'Value', ?FieldContract $valueField = null) ``` -- `$value` - заголовок поля "значение", -- `$valueField` - возможность заменить поле "значение" на своё (по умолчанию — `Text`). +- `$value` - заголовок поля. Используется для поля `Text` по умолчанию. +- `$valueField` - поле значения, если нужно заменить `Text` на другое поле. Пример: ```php -Json::make('Data') +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:2] +use MoonShine\UI\Fields\Json; + +Json::make('Tags', 'tags') ->onlyValue() ``` -![json_only_value](https://raw.githubusercontent.com/moonshine-software/doc/4.x/resources/screenshots/json_only_value.png#light) -![json_only_value_dark](https://raw.githubusercontent.com/moonshine-software/doc/4.x/resources/screenshots/json_only_value_dark.png#dark) +Данные будут храниться как JSON-массив значений: - -## Режим "Объект" +```json +[ + "lorem", + "ipsum" +] +``` -В большинстве случаев поле `Json` работает с массивом объектов через `TableBuilder`. -Однако возможен и режим работы с объектом, например, `{"title": "Title", "active": false}`. -Для этого используется метод `object()`. +Если нужно заменить поле значения, передайте `$valueField`: -Пример: +```php +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:3] +use MoonShine\UI\Fields\Json; +use MoonShine\UI\Fields\Select; + +Json::make('Contacts', 'contacts') + ->onlyValue( + valueField: Select::make('Type') + ->options([ + 'vk' => 'VK', + 'email' => 'E-mail', + ]), + ) +``` + + + +## Режим "Объект" + +По умолчанию `Json` работает с массивом объектов. Метод `object()` используется, когда в колонке должен храниться один JSON-объект, например `{"title": "Title", "active": false}`. ```php -Json::make('Product Options', 'options') +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:4] +use MoonShine\UI\Fields\Json; +use MoonShine\UI\Fields\Switcher; +use MoonShine\UI\Fields\Text; + +Json::make('Settings', 'settings') ->fields([ Text::make('Title'), Switcher::make('Active'), @@ -153,14 +247,21 @@ Json::make('Product Options', 'options') ->object() ``` +При использовании `object()` добавление и удаление строк недоступно. В интерфейсе отображаются только значения, заданные через `fields()`. + -## Вложенные Json -Для создания более сложных структур может понадобиться использование вложенных полей `Json` и **MoonShine** это позволяет. +## Вложенные Json -Пример: +Внутри `Json` можно использовать другое поле `Json`, если нужно описать более сложную структуру данных. ```php +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:4] +use MoonShine\UI\Fields\Json; +use MoonShine\UI\Fields\Number; +use MoonShine\UI\Fields\Text; + Json::make('Products', 'products') ->fields([ Text::make('Name', 'name'), @@ -173,7 +274,7 @@ Json::make('Products', 'products') ]) ``` -Результат: +Данные будут храниться с вложенным объектом: ```json [ @@ -187,103 +288,101 @@ Json::make('Products', 'products') ] ``` - -## Значение по умолчанию + + +## Табличный preview -Как и в других полях, здесь есть возможность указать значение по умолчанию с помощью метода `default()`. -В данном случае необходимо передать массив. +По умолчанию preview поля `Json` выводится как список только для чтения, где заголовок каждого поля отображается рядом со значением. +Метод `table()` переводит поле в режим `preview` и выводит значение как таблицу только для чтения. ```php -default(mixed $default) +table(bool $condition = true) ``` Пример: ```php -Json::make('Data') - ->keyValue('Key', 'Value') - ->default([ - [ - 'key' => 'Default key', - 'value' => 'Default value', - ] - ]), +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:3] +use MoonShine\UI\Fields\Json; +use MoonShine\UI\Fields\Text; -Json::make('Product Options', 'options') +Json::make('Products', 'products') ->fields([ - Text::make('Title'), - Text::make('Value'), - Switcher::make('Active'), - ]) - ->default([ - [ - 'title' => 'Default title', - 'value' => 'Default value', - 'active' => true, - ] - ]), - -Json::make('Values') - ->onlyValue() - ->default([ - ['value' => 'Default value'] + Text::make('Name'), + Json::make('Links') + ->fields([ + Text::make('Label'), + Text::make('Url'), + ]), ]) + ->table() ``` - -## Фильтрация "пустых" значений +Поле будет отображаться как таблица, где `Name` и `Links` будут заголовками таблицы. -По умолчанию поле `Json` фильтрует все пустые значения, но это поведение можно отключить. +Также можно включить табличный preview только для вложенного поля `Json`: ```php -Json::make('data')->stopFilteringEmpty() +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:3] +use MoonShine\UI\Fields\Json; +use MoonShine\UI\Fields\Text; + +Json::make('Products', 'products') + ->fields([ + Text::make('Name'), + Json::make('Links') + ->fields([ + Text::make('Label'), + Text::make('Url'), + ]) + ->table(), + ]) ``` + ## Добавление/Удаление -По умолчанию поле `Json` содержит только один элемент. -Метод `creatable()` позволяет добавлять новые элементы, а `removable()` — удалять их. +По умолчанию строки можно добавлять и удалять. +Метод `creatable()` управляет добавлением новых строк, а `removable()` - удалением существующих. ```php creatable( Closure|bool|null $condition = null, ?int $limit = null, ?ActionButtonContract $button = null, + bool $hideButton = false, ) ``` -- `$condition` - условие, при котором метод должен быть применён, -- `$limit` - ограничение на количество возможных элементов, -- `$button` - возможность заменить кнопку добавления на свою. - -```php -removable( - Closure|bool|null $condition = null, - array $attributes = [], -) -``` - -- `$condition` - условие, при котором метод должен быть применён, -- `$attributes` - HTML атрибуты для кнопки удаления. +- `$condition` - условие, при котором добавление строк доступно. +- `$limit` - максимальное количество строк. +- `$button` - кастомная кнопка добавления. +- `$hideButton` - скрывает кнопку добавления, не отключая возможность добавления строк на уровне поля. -Пример: +Если указан `$limit`, кнопка добавления остается видимой, но блокируется при достижении лимита. ```php -Json::make('Data') - ->keyValue() +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:3] +use MoonShine\UI\Fields\Json; +use MoonShine\UI\Fields\Text; + +Json::make('Product Options', 'options') + ->fields([ + Text::make('Title'), + Text::make('Value'), + ]) ->creatable(limit: 6) - ->removable() ``` -![json_removable](https://raw.githubusercontent.com/moonshine-software/doc/4.x/resources/screenshots/json_removable.png#light) -![json_removable_dark](https://raw.githubusercontent.com/moonshine-software/doc/4.x/resources/screenshots/json_removable_dark.png#dark) - -### Кастомизация кнопки добавления +Кастомизация кнопки добавления: ```php // torchlight! {"summaryCollapsedIndicator": "namespaces"} -// [tl! collapse:2] +// [tl! collapse:3] use MoonShine\UI\Components\ActionButton; use MoonShine\UI\Fields\Json; @@ -294,66 +393,69 @@ Json::make('Data') ) ``` -### HTML атрибуты для кнопки удаления +Скрытие кнопки добавления: ```php -Json::make('Data', 'data.content') +Json::make('Data') ->fields([ Text::make('Title'), - Image::make('Image'), Text::make('Value'), ]) - ->removable(attributes: ['@click.prevent' => 'customAsyncRemove']) - ->creatable() + ->creatable(hideButton: true) ``` - -## Вертикальный режим - -Метод `vertical()` позволяет изменить отображение таблицы из горизонтального режима на вертикальный. - -Пример: +Метод `removable()` управляет отображением кнопки удаления строки. ```php -Json::make('Data') - ->vertical() +removable( + Closure|bool|null $condition = null, + array $attributes = [], +) ``` -![json_vertical](https://raw.githubusercontent.com/moonshine-software/doc/4.x/resources/screenshots/json_vertical.png#light) -![json_vertical_dark](https://raw.githubusercontent.com/moonshine-software/doc/4.x/resources/screenshots/json_vertical_dark.png#dark) +- `$condition` - условие, при котором удаление строк доступно. +- `$attributes` - HTML-атрибуты для кнопки удаления. - -## Сортировка перетаскиванием - -Даёт возможность перетаскивать строки, тем самым изменяя сортировку. -По умолчанию режим включён. Если требуется его отключить, вызовите метод `reorderable(false)`. +При `removable(false)` пользователь сможет добавлять новые строки, но не сможет удалять существующие. ```php -->reorderable(false) -``` - -> [!NOTE] -> Если необходимо указать обработчик (endpoint), воспользуйтесь методом `modifyTable` и задайте `reorderable($url)` через `TableBuilder`. +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:3] +use MoonShine\UI\Fields\Json; +use MoonShine\UI\Fields\Text; - -## Применение в фильтрах +Json::make('Product Options', 'options') + ->fields([ + Text::make('Title'), + Text::make('Value'), + ]) + ->removable(false) +``` -Если поле используется в фильтрах, необходимо включить режим фильтрации с помощью метода `filterMode()`. -Этот метод адаптирует поведение поля для фильтрации и отключает возможность добавления новых элементов. +HTML-атрибуты для кнопки удаления: ```php -Json::make('Data') +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:4] +use MoonShine\UI\Fields\Image; +use MoonShine\UI\Fields\Json; +use MoonShine\UI\Fields\Text; + +Json::make('Data', 'data.content') ->fields([ - Text::make('Title', 'title'), - Text::make('Value', 'value') + Text::make('Title'), + Image::make('Image'), + Text::make('Value'), ]) - ->filterMode() + ->removable(attributes: ['@click.prevent' => 'customAsyncRemove']) + ->creatable() ``` + ## Кнопки -Метод `buttons()` позволяет переопределить кнопки, используемые в поле. +Метод `buttons()` позволяет переопределить кнопки, используемые в строках поля. По умолчанию доступна только кнопка удаления. ```php @@ -363,6 +465,13 @@ buttons(array $buttons) Пример: ```php +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:5] +use MoonShine\UI\Components\ActionButton; +use MoonShine\UI\Fields\Image; +use MoonShine\UI\Fields\Json; +use MoonShine\UI\Fields\Text; + Json::make('Data', 'data.content') ->fields([ Text::make('Title'), @@ -374,75 +483,80 @@ Json::make('Data', 'data.content') ->icon('trash') ->onClick(fn() => 'remove()', 'prevent') ->secondary() - ->showInLine() + ->showInLine(), ]) ``` + ## Модификаторы -Поле `Json` предоставляет возможность модифицировать кнопки или таблицу в режимах "preview" или "default", вместо их полного замещения. +Поле `Json` позволяет модифицировать кнопки в режимах `preview` или `default`, не заменяя их полностью. +Для табличного preview также доступен модификатор таблицы. -### Модификатор кнопки удаления +### Модификатор кнопки добавления -Метод `modifyRemoveButton()` позволяет изменить кнопку удаления. +Метод `modifyCreateButton()` позволяет изменить кнопку добавления. ```php /** - * @param Closure(ActionButton $button, self $field): ActionButton $callback + * @param Closure(ActionButton $button, self $field): ActionButton $callback */ -modifyRemoveButton(Closure $callback) +modifyCreateButton(Closure $callback) ``` Пример: ```php // torchlight! {"summaryCollapsedIndicator": "namespaces"} -// [tl! collapse:2] +// [tl! collapse:3] use MoonShine\UI\Components\ActionButton; use MoonShine\UI\Fields\Json; Json::make('Data') - ->modifyRemoveButton( - fn(ActionButton $button) => $button->customAttributes([ - 'class' => 'btn-secondary' + ->creatable() + ->modifyCreateButton( + fn(ActionButton $button): ActionButton => $button->customAttributes([ + 'class' => 'btn-primary', ]) ) ``` -### Модификатор кнопки добавления +### Модификатор кнопки удаления -Метод `modifyCreateButton()` позволяет изменить кнопку добавления. +Метод `modifyRemoveButton()` позволяет изменить кнопку удаления. ```php /** - * @param Closure(ActionButton $button, self $field): ActionButton $callback + * @param Closure(ActionButton $button, self $field): ActionButton $callback */ -modifyCreateButton(Closure $callback) +modifyRemoveButton(Closure $callback) ``` +Пример: + ```php // torchlight! {"summaryCollapsedIndicator": "namespaces"} -// [tl! collapse:2] +// [tl! collapse:3] use MoonShine\UI\Components\ActionButton; use MoonShine\UI\Fields\Json; Json::make('Data') - ->creatable() - ->modifyCreateButton( - fn(ActionButton $button) => $button->customAttributes([ - 'class' => 'btn-primary' + ->modifyRemoveButton( + fn(ActionButton $button): ActionButton => $button->customAttributes([ + 'class' => 'btn-secondary', ]) ) ``` ### Модификатор таблицы -Метод `modifyTable()` позволяет модифицировать таблицу (`TableBuilder`) для всех визуальных режимов поля. +Метод `modifyTable()` позволяет модифицировать таблицу `TableBuilder` при выводе поля `Json` в preview-режиме. +Метод применяется только для табличного preview, то есть когда поле рендерится через `preview()` или `previewMode()` и включен метод `table()`. ```php /** - * @param Closure(TableBuilder $table, bool $preview): TableBuilder $callback + * @param Closure(TableBuilder $table, bool $preview): TableBuilder $callback */ modifyTable(Closure $callback) ``` @@ -451,14 +565,275 @@ modifyTable(Closure $callback) ```php // torchlight! {"summaryCollapsedIndicator": "namespaces"} -// [tl! collapse:2] +// [tl! collapse:3] use MoonShine\UI\Components\Table\TableBuilder; use MoonShine\UI\Fields\Json; Json::make('Data') + ->table() ->modifyTable( - fn(TableBuilder $table, bool $preview) => $table->customAttributes([ - 'style' => 'width: 50%;' + fn(TableBuilder $table, bool $preview): TableBuilder => $table->customAttributes([ + 'style' => 'width: 20%;', ]) ) ``` + +Также можно использовать совместимые настройки `TableBuilder`, которые поддерживает текущий табличный шаблон: + +```php +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:3] +use MoonShine\UI\Components\Table\TableBuilder; +use MoonShine\UI\Fields\Json; + +Json::make('Data') + ->table() + ->modifyTable( + fn(TableBuilder $table): TableBuilder => $table + ->simple() + ->sticky() + ) +``` + +Для строк и ячеек доступны `trAttributes()` и `tdAttributes()`: + +```php +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:3] +use MoonShine\UI\Components\Table\TableBuilder; +use MoonShine\UI\Fields\Json; + +Json::make('Data') + ->table() + ->modifyTable( + fn(TableBuilder $table): TableBuilder => $table + ->trAttributes(fn(): array => ['style' => 'background: red']) + ->tdAttributes(fn(): array => ['style' => 'background: blue']) + ) +``` + + + +## Сортировка перетаскиванием + +По умолчанию сортировка строк перетаскиванием выключена. + +Метод `reorderable()` управляет отображением кнопки перетаскивания строки. + +```php +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:3] +use MoonShine\UI\Fields\Json; +use MoonShine\UI\Fields\Text; + +Json::make('Product Options', 'options') + ->fields([ + Text::make('Title'), + Text::make('Value'), + ]) + ->reorderable() +``` + +Чтобы явно выключить сортировку перетаскиванием, укажите `false`: + +```php +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:3] +use MoonShine\UI\Fields\Json; +use MoonShine\UI\Fields\Text; + +Json::make('Product Options', 'options') + ->fields([ + Text::make('Title'), + Text::make('Value'), + ]) + ->reorderable(false) +``` + + + +## Сообщение при отсутствии элементов + +Когда в поле `Json` нет строк, в интерфейсе отображается пустой блок. +Метод `emptyMessage()` управляет текстом внутри этого блока. + +```php +emptyMessage(string $message) +``` + +Пример: + +```php +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:3] +use MoonShine\UI\Fields\Json; +use MoonShine\UI\Fields\Text; + +Json::make('Product Options', 'options') + ->fields([ + Text::make('Title'), + Text::make('Value'), + ]) + ->emptyMessage('No options added') +``` + +Для вложенных полей `Json` можно задать отдельное сообщение: + +```php +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:3] +use MoonShine\UI\Fields\Json; +use MoonShine\UI\Fields\Text; + +Json::make('Products', 'products') + ->fields([ + Text::make('Name'), + Json::make('Links') + ->fields([ + Text::make('Label'), + Text::make('Url'), + ]) + ->emptyMessage('No links added'), + ]) +``` + + + +## Применение в фильтрах + +Если поле используется в фильтрах, включите режим фильтрации с помощью метода `filterMode()`. +Он адаптирует поведение поля для фильтра и отключает добавление новых строк. + +```php +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:3] +use MoonShine\UI\Fields\Json; +use MoonShine\UI\Fields\Text; + +Json::make('Data') + ->fields([ + Text::make('Title', 'title'), + Text::make('Value', 'value'), + ]) + ->filterMode() +``` + +Для вложенного `Json` режим фильтрации задается отдельно: + +```php +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:3] +use MoonShine\UI\Fields\Json; +use MoonShine\UI\Fields\Text; + +Json::make('Data') + ->fields([ + Text::make('Title', 'title'), + Json::make('Links', 'links') + ->fields([ + Text::make('Label', 'label'), + Text::make('Url', 'url'), + ]) + ->filterMode(), + ]) +``` + + + +## Фильтрация "пустых" значений + +По умолчанию поле `Json` фильтрует все пустые значения, но это поведение можно отключить. + +```php +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:2] +use MoonShine\UI\Fields\Json; + +Json::make('Data', 'data') + ->stopFilteringEmpty() +``` + + + +## Значение по умолчанию + +Как и в других полях, значение по умолчанию задается методом `default()`. +Для `Json` необходимо передать массив объектов. + +```php +// torchlight! {"summaryCollapsedIndicator": "namespaces"} +// [tl! collapse:3] +use MoonShine\UI\Fields\Json; +use MoonShine\UI\Fields\Text; + +Json::make('Product Options', 'options') + ->fields([ + Text::make('Title'), + Text::make('Value'), + ]) + ->default([ + [ + 'title' => 'Default title', + 'value' => 'Default value', + ], + ]) +``` + + + +## Использование в blade + +Компонент поля можно использовать напрямую в Blade-шаблонах: + +```bladehtml + +``` + +Возможные атрибуты: + +```bladehtml + +```