【问题标题】:Laravel Nova populate field with contents of another field on createLaravel Nova 在创建时使用另一个字段的内容填充字段
【发布时间】:2019-08-02 14:53:21
【问题描述】:

我在 Nova 中定义了一些资源,但遇到了一些问题。我有一个Team 资源具有字段namedisplay_name。我只希望在仪表板上可见display_name 可以使用,但是我拥有Team 模型的方式,name 通过将display_name 变成一个slug 来填充。有没有办法在创建资源时根据display_name 的内容用 Nova 填充name

Text::make('Name')->displayUsing(function(){
                return Str::slug($this->display_name, '_');
            })->hideFromIndex()
                ->hideFromDetail()
                ->hideWhenCreating()
                ->hideWhenUpdating(),

            Text::make('Display Name')
                ->rules('required', 'max:254')
                ->creationRules('unique:teams,name')
                ->updateRules('unique:teams,name,{{resourceId}}'),

            Textarea::make('Description')
                ->rules('required'),

这就是我现在所拥有的,它确实为name 提供了正确的输出,其中包含已经创建的资源,但是当我尝试创建一个新团队时,我收到了这个错误:

SQLSTATE[HY000]: General error: 1364 Field 'name' doesn't have a default value (SQL: insert into 'teams' ('display_name', 'description', 'updated_at', 'created_at')

【问题讨论】:

    标签: php laravel laravel-nova


    【解决方案1】:

    你可以使用 Laravel Mutator 来解决这个问题。在这里阅读:

    https://laravel.com/docs/5.8/eloquent-mutators

    参考我的代码:

    // app\Team.php
    <?php
    
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    use Illuminate\Support\Str;
    
    class Team extends Model
    {
        public function setDisplayNameAttribute($value)
        {
            $this->attributes['display_name'] = $value;
            $this->attributes['name'] = Str::slug($this->display_name, '_');
        }
    }
    
    // app\Nova\Team.php
        public function fields(Request $request)
        {
            return [
                ID::make()->sortable(),
                Text::make('Display Name','display_name'),
                Text::make('Name')->onlyOnIndex(),
                Text::make('Description'),
            ];
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-05
      • 2019-06-12
      • 2016-12-22
      • 1970-01-01
      相关资源
      最近更新 更多