JSON format field handling

The dcat-admin form provides the following components to handle JSON formatted fields, which are convenient for handling JOSN formatted objects, 1D arrays, 2D arrays, etc.

KeyValue object (keyValue)

JSON format field handling - 图1

If your field stores a variable key in the {"field": "value"} format, you can use the keyValue component:

  1. $form->keyValue('column_name');
  2. // Set the validation rule
  3. $form->keyValue('column_name')->rules('required|min:5');

Custom key names and translations of key titles

  1. $form->keyValue(...) ->setKeyLabel('KeyName')->setValueLabel('KeyValue');

Fixed key-value objects (embeds)

JSON format field handling - 图2

Used to process mysql‘s JSON type field data or mongodb‘s object type data, or store multiple field data values as JSON strings in mysql‘s string type fields.

Applies to fields of type JSON with a fixed key value

  1. $form->embeds('column_name', function ($form) {
  2. $form->text('key1')->required();
  3. $form->email('key2')->required();
  4. $form->datetime('key3');
  5. $form->dateRange('key4', 'key5', 'scope')->rules('required');
  6. })->saving(funtion ($v) {
  7. // Converted to json format for storage
  8. return json_encode($v);
  9. });
  10. // Custom TITLE
  11. $form->embeds('column_name', 'Field TITLE', function ($form) {
  12. ...
  13. });

The method calls for building form elements inside the callback function are the same as outside.

one-dimensional array (list)

JSON format field handling - 图3

If your field is used to store a one-dimensional array of ["foo", "Bar"] format, you can use the list component:

  1. $form->list('column_name');
  2. // Setting the validation rule
  3. $form->list('column_name')->rules('required|min:5');
  4. // Set the maximum and minimum number of elements
  5. $form->list('column_name')->max(10)->min(5);

Two-dimensional array (table)

JSON format field handling - 图4

If a field stores a two-dimensional array in json format, the table form component can be used for fast editing:

  1. $form->table('column_name', function ($table) {
  2. $table->text('key');
  3. $table->text('value');
  4. $table->textarea('desc');
  5. })->saving(function ($v) {
  6. return json_encode($v);
  7. });

This component is similar to the hasMany component, but is used to handle the case of a single field, for simple two-dimensional data.

Two-dimensional arrays (array)

JSON format field handling - 图5

If a field stores a two-dimensional array in json format, and there are more fields, you can use the array form component for fast editing:

  1. $form->array('column_name', function ($table) {
  2. $table->text('key');
  3. $table->text('value');
  4. $table->textarea('desc');
  5. })->saveAsJson();