我需要根据当前页面类型index/create/edit/view
自定义一些Laravel Filament v3资源表单
字段/元素。例如,隐藏视图页面上的某些操作字段。
<?php
namespace App\Filament\Resources;
use App\Filament\Resources\BarResource\Pages;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Form;
class BarResource extends \Filament\Resources\Resource
{
public static function getPages(): array
{
return [
'index' => Pages\ListBars::route('/'),
'create' => Pages\CreateBar::route('/create'),
'edit' => Pages\EditBar::route('/{record:uuid}/edit'),
'view' => Pages\ViewBar::route('/{record:uuid}/view'),
];
}
public static function form(Form $form): Form
{
return $form
->schema([
TextInput::make('name')
->hidden(function () {
//do something in cases of edit/view states, something like $state
/*switch ($state) {
case 'view':
return true;
break;
}*/
}),
]);
}
}
有什么想法如何在表单中实现切换(获取当前)资源页面类型吗?
💡我有一个解决问题的想法。
下面的示例基于
edit
上下文/操作。 ⚠️ 记住:你还必须用create/view/index
上下文来完成它。让我们创建一个公共属性 $crud
来确定给定资源类支持哪个上下文/操作。
CreateRecord
班级
\App\Override\Filament\Resources\Pages\CreateRecord
EditRecord
班级
\应用程序\覆盖\灯丝\资源\页面\编辑记录
ViewRecord
班级
\应用程序\覆盖\灯丝\资源\页面\ViewRecord
ListRecords
班级
\应用程序\覆盖\灯丝\资源\页面\ListRecords
app\Override\Filament\Resources\Pages\EditRecord.php
<?php
namespace App\Override\Filament\Resources\Pages;
use Filament\Resources\Pages\EditRecord as BaseEditRecord;
class EditRecord extends BaseEditRecord
{
public string $crud = 'edit';
}
app\Filament\Resources\BarResource\Pages\EditBar.php
<?php
namespace App\Filament\Resources\BarResource\Pages;
use App\Override\Filament\Resources\Pages\EditRecord;
class EditBar extends EditRecord
{
//your edit resource code
}
CreateRecord
特质
\App\Traits\Filament\Resources\Pages\CreateRecord
EditRecord
特质
\App\Traits\Filament\Resources\Pages\EditRecord
ViewRecord
特质
\App\Traits\Filament\Resources\Pages\ViewRecord
ListRecords
特质
\App\Traits\Filament\Resources\Pages\ListRecords
app\Traits\Filament\Resources\Pages\EditRecord.php
<?php
namespace App\Traits\Filament\Resources\Pages;
trait EditRecord
{
public $crud = 'edit';
}
app\Filament\Resources\BarResource\Pages\EditBar.php
<?php
namespace App\Filament\Resources\BarResource\Pages;
use Filament\Resources\Pages\EditRecord;
class EditBar extends EditRecord
{
//our trait
use \App\Traits\Filament\Resources\Pages\EditRecord;
//your edit resource code
}
app\Filament\Resources\BarResource.php
现在您可以切换
$form->getLivewire()->crud
来获取当前表单上下文/操作。
<?php
namespace App\Filament\Resources;
use Filament\Forms\Form;
use Filament\Resources\Resource;
class BarResource extends Resource
{
//your code...
public static function form(Form $form): Form
{
$context = $form->getLivewire()->crud;
return $form
->schema([
TextInput::make('name')
->hidden(function () use ($context) {
switch ($context) {
case 'edit':
//code for edit
break;
case 'view':
//code for view
break;
}
}),
]);
}
}