问题: - 使用 Tabs 组件时,每个 Tab 中的 CheckboxList 都使用相同的字段名 'permissions' - 导致字段冲突,无法正确加载和保存已有权限 解决方案: - 为每个模块使用唯一的字段名(permissions_document, permissions_user 等) - 添加 afterStateHydrated 钩子,在编辑时自动加载该模块的已有权限 - 添加隐藏字段 all_permissions 收集所有模块的权限 - 在 mutateFormDataBeforeSave/mutateFormDataBeforeCreate 中处理权限数据 - 在 afterSave/afterCreate 中使用 syncPermissions 同步权限到数据库 改进: - RoleResource: 编辑角色时,每个模块的权限会自动勾选显示 - UserResource: 编辑用户时,直接权限会自动勾选显示 - 保存时正确收集所有模块的权限并同步到数据库 - super-admin 角色的权限字段保持禁用状态 现在编辑角色或用户时,已有的权限会正确显示为勾选状态
51 lines
1.3 KiB
PHP
51 lines
1.3 KiB
PHP
<?php
|
|
|
|
namespace App\Filament\Resources\RoleResource\Pages;
|
|
|
|
use App\Filament\Resources\RoleResource;
|
|
use Filament\Resources\Pages\CreateRecord;
|
|
|
|
class CreateRole extends CreateRecord
|
|
{
|
|
protected static string $resource = RoleResource::class;
|
|
|
|
protected function getRedirectUrl(): string
|
|
{
|
|
return $this->getResource()::getUrl('index');
|
|
}
|
|
|
|
protected function getCreatedNotificationTitle(): ?string
|
|
{
|
|
return '角色创建成功';
|
|
}
|
|
|
|
protected function mutateFormDataBeforeCreate(array $data): array
|
|
{
|
|
// 从 all_permissions 字段获取权限列表
|
|
if (isset($data['all_permissions'])) {
|
|
$permissions = $data['all_permissions'];
|
|
unset($data['all_permissions']);
|
|
|
|
// 保存权限到记录中,稍后在 afterCreate 中同步
|
|
$this->permissions = $permissions;
|
|
}
|
|
|
|
// 移除所有 permissions_* 字段
|
|
foreach ($data as $key => $value) {
|
|
if (str_starts_with($key, 'permissions_')) {
|
|
unset($data[$key]);
|
|
}
|
|
}
|
|
|
|
return $data;
|
|
}
|
|
|
|
protected function afterCreate(): void
|
|
{
|
|
// 同步权限
|
|
if (isset($this->permissions)) {
|
|
$this->record->syncPermissions($this->permissions);
|
|
}
|
|
}
|
|
}
|