在Laravel Nova(v1.0.3)中,有几种方法可以对资源字段的可见性进行细粒度控制(canSee,showOnDetail等)。我找不到任何控制字段是否可编辑的方法。如何显示字段,但阻止用户编辑它(使其只读)?
例如,我想显示“Created At”字段,但我不希望用户能够更改它。
此功能已在v1.1.4(2018年10月1日)中添加。
用法示例:
Text:: make('SomethingImportant')
->withMeta(['extraAttributes' => [
'readonly' => true
]]),
由于App\Laravel\Nova\Fields\Field
是可宏的,因此您可以轻松添加自己的方法,使其成为只读,e.x。
在App\Providers\NovaServiceProvider
中,您可以在parent::boot()
调用后添加此功能
\Laravel\Nova\Fields\Field::macro('readOnly', function(){
$this->withMeta(['extraAttributes' => [
'readonly' => true
]]);
return $this;
});
然后你可以像这样链接它
Text::make("UUID")->readOnly()->help('you can not edit this field');
从v2.0.1开始,readonly()是本机的,接受回调,闭包或布尔值,可以简单地调用为:
Text::make('Name')->readonly(true)
这可能是在此版本之前添加的,但更改日志未指定是否是这种情况。
从1.0.3开始,我不相信有办法做到这一点(在源文件中看不到任何内容)。
但是,您可以快速创建自己的“ReadOnly”字段,因为Nova可以很容易地添加更多字段类型。
我可能只是耐心等待 - 将字段添加到字段的功能可能是未来版本中的一项功能。
像这样的东西会很酷:
Text::make('date_created')
->sortable()
->isReadOnly()
要么
Text::make('date_created')
->sortable()
->attributes(['readonly'])
您还可以使用canSee
功能。在我的情况下,我无法使用withMeta
解决方案,因为我需要我的一些用户(管理员)能够编辑该字段,但不能使用常规用户。
例:
Number::make('Max Business Locations')
->canSee(function ($request) {
//checks if the request url ends in 'update-fields', the API
//request used to get fields for the "/edit" page
if ($request->is('*update-fields')) {
return $request->user()->can('edit-subscription');
} else {
return true;
}
}),