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

Laravel Filament表单如何预填充文本字段?获取最大发票号+1并禁用

解决方案

1. 基础实现(适用于纯数字编号)

假设你的数据模型是Invoice,在对应的Filament Resource类的form方法中,直接计算并预填编号,同时禁用字段:

use Filament\Forms\Components\TextInput;
use App\Models\Invoice;

public static function form(Form $form): Form
{
    // 处理空表场景,空表时默认编号为1
    $nextInvoiceNumber = Invoice::max('invoice_number') ? (Invoice::max('invoice_number') + 1) : 1;

    return $form
        ->schema([
            // 其他表单字段...
            TextInput::make('invoice_number')
                ->label('发票编号')
                ->default($nextInvoiceNumber)
                ->disabled() // 固定字段禁用状态
                ->required(), // 按需开启必填校验
            // 其他表单字段...
        ]);
}

2. 带前缀的编号处理(如INV-2024-001)

如果你的发票编号包含前缀或日期格式,需要先提取数字部分再计算:

use Filament\Forms\Components\TextInput;
use App\Models\Invoice;

public static function form(Form $form): Form
{
    $lastInvoice = Invoice::orderBy('invoice_number', 'desc')->first();
    if ($lastInvoice) {
        // 提取编号末尾的数字部分,加1后补零格式化
        $numPart = intval(substr($lastInvoice->invoice_number, -3)) + 1;
        $nextInvoiceNumber = 'INV-' . date('Y') . '-' . str_pad($numPart, 3, '0', STR_PAD_LEFT);
    } else {
        // 空表时生成初始编号
        $nextInvoiceNumber = 'INV-' . date('Y') . '-001';
    }

    return $form
        ->schema([
            // 其他表单字段...
            TextInput::make('invoice_number')
                ->label('发票编号')
                ->default($nextInvoiceNumber)
                ->disabled()
                ->required(),
            // 其他表单字段...
        ]);
}

3. 并发安全优化(可选)

如果系统存在多用户同时创建发票的场景,建议把编号生成逻辑放到模型的creating事件中,避免重复编号:

// 在Invoice模型中添加启动逻辑
protected static function booted()
{
    static::creating(function ($invoice) {
        $invoice->invoice_number = Invoice::max('invoice_number') ? (Invoice::max('invoice_number') + 1) : 1;
        // 带前缀的编号逻辑也可以放在这里
    });
}

此时Resource的表单只需保留禁用配置即可:

TextInput::make('invoice_number')
    ->label('发票编号')
    ->disabled()
    ->required(),

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 12:36:22