如何在Laravel Nova Action模态框中为BooleanGroup设置预勾选复选框
Laravel Nova BooleanGroup 字段设置默认选中方案
通用解决方案(适用于 Nova 4.x 及以上版本)
直接调用default()方法即可设置默认选中项,方法接收数组参数,键为你要选中的选项的标识,值设为true即代表默认选中。
注意:你当前配置的
options为索引数组,每个选项的实际标识为对应数组下标(0对应one、1对应two、2对应three、3对应four),后续调整选项顺序容易出现默认值匹配错误,建议先改为键值一致的关联数组更稳妥。
示例代码如下:
return [ BooleanGroup::make('Tagss') ->options([ 'one' => 'one', 'two' => 'two', 'three' => 'three', 'four' => 'four' ]) ->default([ 'two' => true // 要默认选中的选项键对应值设为true即可 ]), ];
如果要保留原索引数组写法,two对应下标为1,默认值写法如下:
return [ BooleanGroup::make('Tagss') ->options([ 'one', 'two', 'three', 'four' ]) ->default([1 => true]), ];
低版本兼容方案(适用于 Nova 3.x 版本)
如果使用的是Nova 3.x旧版本,default()方法不生效,可以通过withMeta()手动指定默认值:
return [ BooleanGroup::make('Tagss') ->options([ 'one' => 'one', 'two' => 'two', 'three' => 'three', 'four' => 'four' ]) ->withMeta([ 'value' => ['two' => true] ]), ];
动态默认值配置
如果需要根据当前操作的资源数据动态生成默认选中项,可以在Action的fields方法中接收模型实例参数来处理:
public function fields(NovaRequest $request, $model = null) { // 可根据$model的字段值自定义默认选中逻辑 $defaultSelected = $model?->type === 2 ? ['one' => true, 'two' => true] : ['two' => true]; return [ BooleanGroup::make('Tagss') ->options([ 'one' => 'one', 'two' => 'two', 'three' => 'three', 'four' => 'four' ]) ->default($defaultSelected), ]; }
内容的提问来源于stack exchange,提问作者Danzzz
相关产品推荐
相关产品推荐

