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

How to set a Laravel Nova field to display as readonly or protected?

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

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

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

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

不过我可能会耐心等待 - 向字段添加属性的功能可能会成为未来版本中的一项功能。

像这样的东西会很酷:

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

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

此功能已添加到 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');

您还可以使用 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;
            }
        }),

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

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

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

Nova v2.0 documentation

从 Nova >2.0 开始,您可以使用带有回调的只读方法并检查资源:

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;
    }),

2021 年 7 月,对于 Nova 版本 3.0readonly 方法可以接受不同类型的参数

默认:

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

除了 之外,还有一种巧妙的方法可以在编辑字段时将其设为只读,而不是在创建时设为只读:

Text::make('Handle')
    ->readonly(fn ($request) => $request->isUpdateOrUpdateAttachedRequest()),

此方法基于 Laravel\Nova\Fields\Field@isRequired,使用相同的验证来获取特定于每个操作的所需规则。