如何将Laravel Nova字段设置为只读或受保护?

问题描述 投票:3回答:5

在Laravel Nova(v1.0.3)中,有几种方法可以对资源字段的可见性进行细粒度控制(canSee,showOnDetail等)。我找不到任何控制字段是否可编辑的方法。如何显示字段,但阻止用户编辑它(使其只读)?

例如,我想显示“Created At”字段,但我不希望用户能够更改它。

laravel-nova
5个回答
9
投票

此功能已在v1.1.4(2018年10月1日)中添加。

  • 允许在text和textarea字段上设置任何属性

用法示例:

Text:: make('SomethingImportant')
    ->withMeta(['extraAttributes' => [
          'readonly' => true
    ]]),

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');

1
投票

从v2.0.1开始,readonly()是本机的,接受回调,闭包或布尔值,可以简单地调用为:

Text::make('Name')->readonly(true)

这可能是在此版本之前添加的,但更改日志未指定是否是这种情况。

Nova v2.0 documentation


0
投票

从1.0.3开始,我不相信有办法做到这一点(在源文件中看不到任何内容)。

但是,您可以快速创建自己的“ReadOnly”字段,因为Nova可以很容易地添加更多字段类型。

我可能只是耐心等待 - 将字段添加到字段的功能可能是未来版本中的一项功能。

像这样的东西会很酷:

Text::make('date_created')
    ->sortable()
    ->isReadOnly()

要么

Text::make('date_created')
    ->sortable()
    ->attributes(['readonly'])

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;
            }
        }),
© www.soinside.com 2019 - 2024. All rights reserved.