You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否将InlineCreateOperation与select2_from_ajax结合实现版本动态加载与inline新增

实现方案

可以实现,这是Backpack for Laravel中InlineCreateOperation与select2_from_ajax字段的常规组合用法,按以下步骤配置即可满足需求:

1. 配置主CRUD的联动选择字段

首先在对应CRUD控制器的操作初始化方法(setupCreateOperation/setupUpdateOperation)中,先添加应用选择字段,再配置关联的版本ajax选择字段:

// 所属应用选择字段
CRUD::field('app_id')
    ->label('所属应用')
    ->type('select2')
    ->entity('app')
    ->attribute('name')
    ->model(App\Models\App::class)
    ->wrapper(['class' => 'form-group col-md-6']);

// 关联应用版本选择字段(带ajax联动+inline创建)
CRUD::field('app_version_id')
    ->label('应用版本')
    ->type('select2_from_ajax')
    ->entity('appVersion')
    ->attribute('version_number')
    ->model(App\Models\AppVersion::class)
    // ajax数据源接口地址
    ->data_source(url('api/app-versions'))
    // 绑定应用字段作为依赖,选中应用后自动刷新版本列表
    ->dependencies(['app_id'])
    ->include_all_form_fields(true)
    ->wrapper(['class' => 'form-group col-md-6'])

2. 给版本字段添加InlineCreate配置

直接在上面的app_version_id字段配置末尾追加inline_create参数,即可启用 inline 新增功能,选中应用后新增版本会自动填充对应应用的外键值:

->inline_create([
    // 定义新增版本弹窗的表单字段
    'fields' => [
        'version_number' => [
            'name' => 'version_number',
            'label' => '版本号',
            'type' => 'text',
            'required' => true,
        ],
        'version_desc' => [
            'name' => 'version_desc',
            'label' => '版本说明',
            'type' => 'textarea',
        ]
    ],
    // 新增完成后自动选中刚创建的版本、刷新版本选项列表
    'force_select' => true,
])

3. 实现ajax数据源接口

新增接口接收联动传递的应用ID参数,返回对应应用的版本列表:

// routes/api.php 中添加路由
Route::get('app-versions', function (\Illuminate\Http\Request $request) {
    $searchKeyword = $request->input('q');
    $versionQuery = \App\Models\AppVersion::where('app_id', $request->input('app_id'));
    
    // 兼容select2的搜索逻辑
    if ($searchKeyword) {
        $versionQuery->where('version_number', 'like', "%{$searchKeyword}%");
    }
    
    return $versionQuery->paginate(10);
});

注意事项

  • 需提前定义好App模型与AppVersion模型的一对多关联关系,AppVersion模型存在app_id外键字段
  • 需确保当前操作用户拥有AppVersion模型的创建权限,否则inline创建按钮不会渲染

内容的提问来源于stack exchange,提问作者Foiret Christophe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 21:15:04