【问题标题】:Laravel Nova Set ID manually on FormLaravel Nova 在表单上手动设置 ID
【发布时间】:2018-12-03 14:46:10
【问题描述】:

我想手动设置我的 ID 因为我的 ID 类型为字符串(varchar)

这是我的模型

<?php

namespace App\Model\Master;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class UnitOfMeasure extends Model 
{

protected $table = 'unit_of_measures';
public $timestamps = true;
public $incrementing = false;

use SoftDeletes;

protected $dates = ['deleted_at'];
protected $fillable = array('id','code', 'description', 'scan_input_required');

public function workCenter()
{
    return $this->hasMany(WorkCenter::class,'unit_of_measures_code','code');
}

但 Nova 总是隐藏 ID 字段。 有没有办法做到这一点?

谢谢

【问题讨论】:

    标签: php laravel laravel-nova


    【解决方案1】:

    如果您查看调用 creation-fields 端点的请求,您会注意到 ID 甚至不在字段列表中。

    Resources 使用的特征 ResolvesFields 正在调用函数 creationFields 来生成要显示在前面的字段列表,它正在调用 removeNonCreationFields

    /**
     * Remove non-creation fields from the given collection.
     *
     * @param  \Illuminate\Support\Collection  $fields
     * @return \Illuminate\Support\Collection
     */
    protected function removeNonCreationFields(Collection $fields)
    {
        return $fields->reject(function ($field) {
            return $field instanceof ListableField ||
                   $field instanceof ResourceToolElement ||
                   $field->attribute === $this->resource->getKeyName() ||
                   $field->attribute === 'ComputedField' ||
                   ! $field->showOnCreation;
        });
    }
    

    并且由于该字段符合此规则:

    $field->attribute === $this->resource->getKeyName()
    

    ID 字段正在被删除。

    要强制该字段,您可以在资源中覆盖该函数:

    /**
     * Remove non-creation fields from the given collection.
     *
     * @param  \Illuminate\Support\Collection  $fields
     * @return \Illuminate\Support\Collection
     */
    protected function removeNonCreationFields(Collection $fields)
    {
        return $fields->reject(function ($field) {
            return $field instanceof ListableField ||
                   $field instanceof ResourceToolElement ||
                   $field->attribute === 'ComputedField' ||
                   ! $field->showOnCreation;
        });
    }
    

    【讨论】:

    • 你拯救了我的一天兄弟.. 谢谢。顺便说一句,你怎么知道创建字段是 Invoke?
    • 对于编辑表单也不要忘记覆盖资源中 ResolveFields.php 中的 removeNonUpdateFields 方法
    • @hendra1 你是什么意思我怎么知道创建字段被调用?
    【解决方案2】:

    我自己也遇到了这个问题,看起来 Nova 已经更新,因此您可以手动将 ID 字段添加到资源:Text::make('ID'),然后您将拥有一个可编辑的 ID 字段。

    这是 github 问题:https://github.com/laravel/nova-issues/issues/268

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-09
      • 1970-01-01
      • 2019-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多