月份组件
php artisan make:form-field MonthDatePickerCopy
该命令创建以下文件
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>
效果: