【问题标题】:Add custom values in drop down in laravel backpack在 laravel 背包的下拉菜单中添加自定义值
【发布时间】:2017-04-25 22:24:24
【问题描述】:

我正在使用 laravel,并且我有两个名为 bundles 和 study 的表。我在 bundleCrudController 的表单中添加了一个下拉字段。但我只想在下拉列表中添加那些由登录用户创建的研究的值,而不是研究表中的所有数据。

这是我在下拉列表中添加数据的代码 -

  $this->crud->addField([
                'name' => 'studies',
                'label' => 'Studies',
                'type' => 'select2_from_array',
                'options' => $this->Study->getUnallocatedStudies($entryId),
                'allows_null' => false,
                'hint' => 'Search for the studies you would like to add to this bundle',
                'tab' => 'Info',
                'allows_multiple' => true
            ]);

      $this->crud->addColumn([
                'label' => 'Studies',
                'type' => "select_multiple",
                'name' => 'bundle_id',
                'entity' => 'studies',
                'attribute' => 'name',
                'model' => "App\Models\Study",
            ]);

所以请帮我解决这个问题,只在登录用户创建的下拉列表中添加那些记录,而不是所有记录。谢谢

【问题讨论】:

  • 使用 model_function 或在 resources/views/vendor/backpack/crud/fields 中创建一个自定义字段并在那里或在研究模型(或您需要的任何模型)中添加条件添加全局范围(检查所有这些解决方案的手册)

标签: laravel laravel-5.4 laravel-backpack


【解决方案1】:

我认为最好的方法是创建一个额外的模型 UserStudy,它:

  • 扩展研究;

  • 具有全局范围,用于过滤当前用户可以看到的内容;

它应该看起来像这样:

<?php

namespace App\Models;

use App\Models\Study;
use Auth;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

class UserStudy extends Study
{
    /**
     * The "booting" method of the model.
     *
     * @return void
     */
    protected static function boot()
    {
        parent::boot();

        // filter out the studies that don't belong to this user
        if (Auth::check()) {
            $user = Auth::user();

            static::addGlobalScope('user_id', function (Builder $builder) use ($user) {
                $builder->where('user_id', $user->id);
            });
        }
    }
}

然后,您就可以在字段定义中使用此 UserStudy 模型,而不是 Study。只需将App\Models\Study 替换为App\Models\UserStudy

希望对您有所帮助。干杯!

【讨论】:

  • 谢谢亲爱的.. 会试试的。
猜你喜欢
  • 1970-01-01
  • 2023-03-04
  • 2023-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-11
  • 1970-01-01
相关资源
最近更新 更多