背包 CRUD 控制器:根据正在编辑的模型显示字段

Backpack CRUD Controller: show fields depending on model is editing

我可以设置 CRUD 控制器以根据模型显示字段的方式进行编辑吗?

示例:我的模型包含以下字段:idtypefield1field2.

对于 type=type1 的模型我只想显示 field1:

$this->crud->addFields([
    ['name' => 'field1', 'label' => 'field1 label']
]);

仅适用于 type=type2 的型号 field2:

$this->crud->addFields([
    ['name' => 'field2', 'label' => 'field2 label']
]);

对于同时具有 type=type3 field1field2 的模型:

$this->crud->addFields([
    ['name' => 'field1', 'label' => 'field1 label'],
    ['name' => 'field2', 'label' => 'field2 label']
]);

this page in the docs 的最底部列出:

Inside your custom field type, you can use these variables:

...

$entry - in the Update operation, the current entry being modified (the actual values);

实现此目的的一种方法是使用自定义字段并利用 $entry 变量。例如,您可以像这样制作 2 个自定义字段:

field1.blade.php

@if(in_array($entry->type, ['type1','type3']))
    {{--  your field content here, see resources/views/vendor/backpack/crud/fields/text.blade.php as an example --}}
@endif

field2.blade.php

@if(in_array($entry->type, ['type2','type3']))
    {{--  you can even pull in the content of an existing field like this  --}}
    @include('crud::fields.text')
@endif

然后,在您的控制器中,您总是会添加这两个字段,并让字段本身完成隐藏正确字段的工作。

 $this->crud->addFields([
        [
            'name' => 'field1', 
            'label' => 'field1 label',
            'type'  => 'field1',
        ],
        [
            'name' => 'field2', 
            'label' => 'field2 label',
            'type'  => 'field2',
        ]
    ]);