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