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

如何在Filament的EditPermohonan类中实现保存前确认模态框

解决方案

要实现保存前弹出带修改摘要的确认模态框,不能在beforeSave()里直接创建Action——这是后端钩子,无法触发前端模态。正确做法是重写表单的保存按钮Action,自定义确认逻辑和模态内容:

<?php 
use Filament\Actions;
use Filament\Actions\Action;
use Filament\Resources\Pages\EditRecord;
use Illuminate\Support\HtmlString;

class EditPermohonan extends EditRecord
{
    protected static string $resource = PermohonanResource::class;

    protected function getHeaderActions(): array
    {
        return [
            Actions\DeleteAction::make(),
        ];
    }

    protected function getRedirectUrl(): ?string
    {
        return $this->getResource()::getUrl('index');
    }

    // 重写表单底部的保存按钮
    protected function getFormActions(): array
    {
        return [
            $this->getSaveFormAction()->requiresConfirmation()
                ->modalContent(function () {
                    // 获取当前模型的所有修改字段
                    $dirtyFields = $this->getRecord()->getDirty();
                    
                    if (empty($dirtyFields)) {
                        return new HtmlString('<p>未检测到任何修改</p>');
                    }

                    // 构建修改摘要的HTML内容
                    $summaryHtml = '<ul>';
                    foreach ($dirtyFields as $field => $newValue) {
                        $oldValue = $this->getRecord()->getOriginal($field);
                        // 字段名转为友好显示格式
                        $fieldLabel = ucfirst(str_replace('_', ' ', $field));
                        
                        $summaryHtml .= sprintf(
                            '<li><strong>%s</strong>: 从 "%s" 修改为 "%s"</li>',
                            $fieldLabel,
                            $oldValue,
                            $newValue
                        );
                    }
                    $summaryHtml .= '</ul>';

                    return new HtmlString($summaryHtml);
                })
                ->modalHeading('确认修改内容')
                ->modalSubmitActionLabel('确认保存'),
            $this->getCancelFormAction(),
        ];
    }
}

关键说明

  • getFormActions()是EditRecord页面用来定义表单底部操作按钮的方法,通过替换默认保存按钮,实现自定义确认逻辑。
  • requiresConfirmation()开启确认模态框,modalContent()用来生成模态框内的修改摘要内容。
  • getDirty()获取模型中被修改的字段集合,getOriginal($field)获取字段修改前的原始值,两者对比生成可读摘要。
  • 使用HtmlString渲染HTML格式的摘要,让内容层级更清晰。

如果需要对特定字段做更友好的显示(比如日期格式化、关联模型名称),可以在循环内针对性处理,示例:

// 日期字段格式化
if (in_array($field, ['tanggal_mohon', 'tanggal_selesai'])) {
    $oldValue = date('Y-m-d', strtotime($oldValue));
    $newValue = date('Y-m-d', strtotime($newValue));
}

// 关联模型显示名称而非ID
if ($field === 'kategori_id') {
    $oldValue = \App\Models\Kategori::find($oldValue)?->nama ?? '无';
    $newValue = \App\Models\Kategori::find($newValue)?->nama ?? '无';
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 21:57:36