首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在repeatable中加载数据而不以JSON格式保存数据的问题Laravel-Backpack

在repeatable中加载数据而不以JSON格式保存数据的问题Laravel-Backpack
EN

Stack Overflow用户
提问于 2021-08-30 17:52:58
回答 1查看 217关注 0票数 0

我使用的是来自Laravel-Backpack的可重复的,我可以将数据保存到两个表中。但是,我无法在尝试编辑销售时加载这些数据。它不会加载通过可重复对象保存的表单中的数据。

示例:

当通过链接查看示例演示时。https://demo.backpackforelaravel.com/admin/dummy/create它将重复字段中的数据转换为JSON,并将其保存在数据库中一个名为Extra的字段中。

在数据库的附加字段中保存的格式:

代码语言:javascript
复制
{
 "simple": "[{\"text\":\"TesteTesteTesteTeste\",\"email\":\"admin@admin\",\"textarea\":\"teste\",\"number\":\"1\",\"float\":\"1\",\"number_with_prefix\":\"1\",\"number_with_suffix\":\"0\",\"text_with_both_prefix_and_suffix\":\"1\",\"password\":\"123\",\"radio\":\"1\",\"checkbox\":\"1\",\"hidden\":\"6318\"}]",
}

在我的例子中,我将数据保存在不同的表中,而不使用JSON。

代码语言:javascript
复制
//My Model
class Sales extends Model

    protected $casts = [
        'id' => 'integer',
        'user_id' => 'integer',
        'date_purchase' => 'date',
        'client_id' => 'integer',
    ];

    public function getProductsAttribute()
    {

        $objects = ItensProducts::where('product_id', $this->id)->get();
        $array = [];

        if (!empty($objects)) {
            foreach ($objects  as $itens) {
                $obj = new stdClass();
                $obj->product_id = "" . $itens->product_id;
                $obj->quantity  = "" . $itens->quantity;

                $categoryProduct = CategoryProduct::where('product_id',  $itens->product_id)->get();

                  $arrayCategoryProduct = [];
                foreach ($categoryProduct  as $stItens) {
                    $arrayCategoryProduct[] = $stItens->name;
                }
                $obj->categories_product = $arrayCategoryProduct;

                $array[] = $obj;
            }
        }
        //Converts JSON to the example of the extra database field 
        $array_result = json_encode(\json_encode($array), JSON_HEX_QUOT | JSON_HEX_APOS);
        $array_result = str_replace(['\u0022', '\u0027'], ["\\\"", "\\'"], $array_result);

        return $array_result;
    }

我的表单:

代码语言:javascript
复制
//SalesCruController.php
protected function setupCreateOperation()
    {
        CRUD::addField([   // repeatable
            'name'  => 'products',
            'label' => 'Produtos(s)',
            'type'  => 'repeatable',
            'fields' => [
                [
                    'name' => 'product_id', 'type' => 'select2', 'label' => 'Produtos',
                    'attribute' => "name",
                    'model' => "App\Models\Product",
                    'entity' => 'products',
                    'placeholder' => "Selecione o Produto",
                    'wrapper'  => [
                        'class' => 'form-group col-md-6'
                    ],
                ],
                [
                    'name' => 'category_id', 'type' => 'select2', 'label' => "Categoria",
                    'attribute' => "name",
                    'model' => "App\Models\CategoryProduct",
                    'entity' => 'categories',
                    'placeholder' => "Selecione uma Categoria",
                ],
                [
                    'name'  => 'quantity',
                    'label' => "Quantidade",
                    'type'  => 'text',
                ],
            ],
            // optional
            'new_item_label'  => 'Adicionar',
            'init_rows' => 1,
            'min_rows' => 1,
            'max_rows' => 3,

        ],);
    }
}

方法存储区

代码语言:javascript
复制
public function store()
    {
        $item = $this->crud->create($this->crud->getRequest()->except(['save_action', '_token', '_method']));

        $products = json_decode($this->crud->getRequest()->input('products'));

        $this->validateRepeatableFields($categoryProduct);

        if (is_array($products)) {

            foreach ($products  as $itens) {

                $obj = new ItensProduct();
                $obj->sale_id =  $item->getKey();
                $obj->product_id = $itens->product_id;
                $obj->quantity  = $itens->quantity;
                $obj->save();

                $categoryProduct = json_decode($itens->categories);

                foreach ($categoryProduct  as $cItens) {
                    $objCat = new CategoryProduct();
                    $objCat->product_id = $obj->getKey();
                    $objCat->name = $cItens;
                    $objCat->save();
                }
            }
        } else {
            \Alert::add('warning', '<b>Preencha os campos de pelo menos um produto.</b>')->flash();
            return redirect('admin/sales/create');
        }
        \Alert::success(trans('backpack::crud.insert_success'))->flash();
        return redirect('admin/sales');
    }

function validateRepeatableFields($categoryProduct)
{
    foreach ($categoryProduct as $group) {
        Validator::make((array)$group, [
            'sale_id' => 'required',
            'product_id' => 'required',
            'quantity' => 'required',
        ], [
            "product_id.required" => "O campo Produto é obrigatório",
            "quantity.required" => "O campo quantidade é obrigatório",
        ])->validate();
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-05 00:37:25

我能够解决将字段返回到可重复表单的问题。

如果有人需要,我想分享这个解决方案。当我试图将来自category_id字段的数据放入json中时出错,该字段是一个向量,它必须像这样返回,如下所示。

{"product_id":"4",数量:"3","category_id":"10,4,8,8"}

向量必须在字符串中,我正在传递字段,但没有将整个向量转换为可重复项所期望的格式的字符串。然后,我在一个字符串中承认了I,最后我承认了内聚,并使用子字符串删除了最后一个virgulation,如下面的代码所示。

通过这种方式,我能够返回字段以及以可重复形式保存在数据库中的适当信息。

代码语言:javascript
复制
     public function getProductsAttribute()
    {
        $objects = ItensProducts::where('product_id', $this->id)->get();
        $response = [];
    
        if (!empty($objects)) {
            foreach ($objects as $itens) {
    
                $categoryProduct = CategoryProduct::where('product_id', $itens->product_id)->get();
    
                $itensCatProd = '';
                foreach ($categoryProduct as $itensCatProd) {
                    $itensCatProd .= $itensCatProd->id . ',';
                };
    
                $response[] = [
                    'product_id' => $itens->product_id,
                    'category_id' => '[' . substr($itensCatProd, 0, -1) . ']',
                    'quantity' => $itens->quantity,
                ];
    
                return json_encode($response);
            }
        }
    }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68988387

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档