laravel-admin form processing json format field

There is a table where a field is in json format and the structure is as follows

[{"name":"1","value":"2"},{"name":"2","value":"1"},{"name":"3","value":"1"},{"name":"4","value":"1"},{"name":"5","value":"1"},{"name":"6","value":"1"},{"name":"7","value":"1"},{"name":"8","value":"1"}]

 

If you want to start editing one by one while editing this item instead of editing the entire string, you need to make the following modifications

First add in the model file corresponding to the table

protected $casts = [
        'item_detail' => 'json',
    ];

item_detail is the field name of the json string. After adding this attribute, laravel-admin will automatically process this field to json_decode it

Then in the controller's form method

$form->table('item_detail','详情', function ($form) {

            $form->text('name');
            $form->text('value');
        });

At this time, editing will display all the key-value pairs. If you want to beautify, use other methods of form to beautify the field.

 

 

Note: After setting the corresponding field in the model to json, the callback method of the corresponding field in the controller detail (data details) method will also be automatically json_decode

$show->field('item_detail', __('详情'))->unescape()->as(function ($content) {
       / * When 
        there is no setting in the model, $ content is automatically converted to an array after setting the json string
        * /
// Remove all item id in the structure data $ item_ids = []; foreach ($ content as $ v) { $item_ids[] = $v['name']; } $item = Item::whereIn('id',$item_ids)->get(); $mapping_arr = []; foreach($item as $v){ $mapping_arr[$v->id] = $v->name; } $return = ''; foreach($content as $v){ if($v['value']==1){ $return = $return."<div class='alert alert-success' role='alert'>{$mapping_arr[$v['name']]}</div>"; }else{ $return = $return."<div class='alert alert-danger' role='alert'>{$mapping_arr[$v['name']]}</div>"; } } return $return; });

 

Guess you like

Origin www.cnblogs.com/zwsblogs/p/12673602.html