如何为字段Laravel Nova指定默认值

hgc7kmma  于 6个月前  发布在  其他
关注(0)|答案(3)|浏览(99)

我想将资源字段的默认值设置为经过身份验证的用户的id。我有一个名为Note的模型,它与GameUser有一对多的关系。

User hasMany Note
Game hasMany Note

Note belongsTo User
Note belongsTo Game

字符串
在Laravel Nova中,我的字段看起来像这样

ID::make()->sortable(),
Text::make('Note', 'note')->onlyOnIndex(),
Textarea::make('Note', 'note')->alwaysShow(),
BelongsTo::make('Game', 'game')->hideWhenCreating()->hideWhenUpdating(),
BelongsTo::make('Created By', 'user', 'App\Nova\User')->hideWhenCreating()->hideWhenUpdating(),
DateTime::make('Created At', 'created_at')->hideWhenCreating(),
DateTime::make('Updated At', 'updated_at')->hideWhenCreating(),


因为我在Game Nova资源上引用Note,所以当我创建Note时,game_id列被正确填充。但是,我希望user_id列是经过身份验证的用户的值。它似乎不是这样工作的,我该如何完成它?

cbeh67ev

cbeh67ev1#

我需要将BelongsTo字段值设置为null,这取决于资源中的其他字段值。这是我如何使用NovaDependencyContainer完成的:

Select::make(__('admin.user.type'), 'user_type')
    ->options([
        'employee' => 'Employee',
        'other_employee' => 'Bank Employee',
    ]),

NovaDependencyContainer::make([
    BelongsTo::make(__('admin.user.employee_id'), 'employee', Employee::class)
        ->required()
        ->searchable(),
])->dependsOn('user_type', 'employee'),
NovaDependencyContainer::make([
    Text::make(__('admin.user.employee_id'), 'employee_id')
        ->readonly()
        ->nullable()
        ->resolveUsing(fn() => null),
])->dependsOn('user_type', 'other_employee'),

字符串

yi0zb3m4

yi0zb3m42#

如果我从BelongsTo::make('Created By', 'user', 'App\Nova\User')->hideWhenCreating()->hideWhenUpdating()行理解正确的话,你试图为列设置一个默认值,而不在表单上显示字段?
我不认为这样做是可能的。一旦你使用hide函数,字段就不会被呈现,也不会随请求沿着传递。我试过了,user_id字段从来没有随请求一起发送。
我认为有两种方法可以做到这一点:
在表单中显示字段,并使用元数据设置默认值(为了更好的测量,可能会将字段设置为只读)。

BelongsTo::make('Created By', 'user', 'App\Nova\User')->withMeta([
    "belongsToId" => auth()->user()->id,
])

字符串
查看Nova文档的这一部分
或者使用Eloquent creating事件。以下内容将进入您的Note模型。

public static function boot()
{
    parent::boot();
    static::creating(function($note)
    {
        $note->user_id = auth()->user()->id;
    });
}


当然,上面的方法有点简单,最好使用适当的事件侦听器。
附件:从体系结构的Angular 来看,我会选择选项2。在不涉及最终用户的情况下设置默认值听起来像是Eloquent模型的工作,而不是Nova表单。

km0tfn4u

km0tfn4u3#

你可以使用一个方法resolveUsing()

<?php

//...

Select::make('My Select', 'my_custom_name')
   ->options(['a' => 'a', 'b' => 'b', 'c' => 'c'])
   ->resolveUsing(function ($value, $resource, $attribute) {
      // $value = model attribute value
      // $attribute = 'my_custom_name'
      return 'b';
});

字符串

相关问题