在Laravel Nova(v1.0.3)中,有几种方法可以对资源字段的可见性进行精细控制(canSee,showOnDetail等)。我找不到控制字段是否可编辑的任何方法。如何显示字段,但阻止用户对其进行编辑(使其变为只读)?
例如,我想显示“创建时间”字段,但我不希望用户能够对其进行更改。
答案 0 :(得分:9)
此功能已在v1.1.4(2018年10月1日)中添加。
用法示例:
Text:: make('SomethingImportant')
->withMeta(['extraAttributes' => [
'readonly' => true
]]),
答案 1 :(得分:2)
由于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');
答案 2 :(得分:1)
As of v2.0.1, readonly() is native and accepts a callback, closure or boolean and can simply be called as:
Text::make('Name')->readonly(true)
This may have been added prior to this version but the changelog does not specify if this is the case.
答案 3 :(得分:1)
从Nova >2.0
开始,您可以将readonly方法与回调一起使用并检查资源:
Text::make("Read Only on Update")
->readonly(function() {
return $this->resource->id ? true : false;
}),
甚至更好:
Text::make("Read Only on Update")
->readonly(function() {
return $this->resource->exists;
}),
答案 4 :(得分:0)
自1.0.3起,我不认为有一种方法可以做到这一点(在源文件中看不到任何内容)。
但是,由于Nova使添加更多字段类型非常容易,因此您可以快速创建自己的“只读”字段。
不过,我可能会耐心等待-在将来的版本中,向字段添加属性的功能很可能会成为功能。
像这样的事情会很酷:
Text::make('date_created')
->sortable()
->isReadOnly()
或
Text::make('date_created')
->sortable()
->attributes(['readonly'])
答案 5 :(得分:0)
您还可以使用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;
}
}),
答案 6 :(得分:0)
2021 年 7 月,对于 Nova 版本 3.0
,readonly
方法可以接受不同类型的参数
默认:
Text::make('Email')->readonly()
直接布尔值:
Text::make('Email')->readonly(true/false)
关闭:
Text::make('Email')->readonly(function ($request) {
return !$request->user()->isNiceDude();
}
在此处阅读更多信息https://nova.laravel.com/docs/3.0/resources/fields.html#readonly-fields