Filament 创建自定义表单组件

月份组件

php artisan make:form-field MonthDatePicker

该命令创建以下文件
App/Forms/Components/MonthDatePicker.php

namespace App\Forms\Components;

use Carbon\Carbon;
use Filament\Forms\Components\Field;

class MonthDatePicker extends Field
{
    protected string $view = 'forms.components.month-date-picker';

    public function setUp(): void
    {
        // 将存储的数据格式化显示样式,否则无法正常渲染,同时使用当前月份作为默认值
        $this->formatStateUsing(function ($state){
            return Carbon::parse($state)->format("Y-m");
        });
    }

    // 因为保存默认样式为字符串 Y-m 如果数据库字段格式为timestamp时,将无法保存
    // 格式化存储样式
    public function getState()
    {
        $state = parent::getState();
        if ($state){
            return Carbon::parse($state)->startOfMonth()->toDateString();
        }
        return null;
    }
}

resources/views/forms/components/month-date-picker.blade.php

<x-dynamic-component
    :component="$getFieldWrapperView()"
    :id="$getId()"
    :label="$getLabel()"
    :label-sr-only="$isLabelHidden()"
    :helper-text="$getHelperText()"
    :hint="$getHint()"
    :hint-action="$getHintAction()"
    :hint-color="$getHintColor()"
    :hint-icon="$getHintIcon()"
    :required="$isRequired()"
    :state-path="$getStatePath()"
>
    @php
        $inputClasses = "text-gray-900 border-gray-300 invalid:text-gray-400block w-full transition duration-75 rounded-lg shadow-sm outline-none focus:border-primary-500 focus:ring-1 focus:ring-inset focus:ring-primary-500";
    @endphp
    <input class="{{$inputClasses}}" type="month" wire:model.defer="{{ $getStatePath() }}">
</x-dynamic-component>

效果:

Filament 创建自定义表单组件

本作品采用《CC 协议》,转载必须注明作者和本文链接
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!