【问题标题】:Get selected value from select_from_array field using laravel 5.2 Backpack使用 laravel 5.2 Backpack 从 select_from_array 字段中获取选定的值
【发布时间】:2017-02-01 06:39:43
【问题描述】:

我在我的新项目中使用 Laravel 5.2 Backpack,我的表单中有一个 select_from_array 字段,这取决于我希望数据显示在另一个 select_from_array 字段中的所选值。不知道该怎么做。请帮我解决一下这个。这是我的代码

控制器.php

public function __construct()
{
    if (Request::segment(3) == 'create') {
        $parentField1 = [
        'name' => 'cat_id',
        'label' => 'Category',
        'type' => 'select_from_array',
        'options' => $this->categories(),
        'allows_null' => false,
        ];
        $parentField = [
            'name' => 'subCat_id',
            'label' => 'SubCategory',
            'type' => 'select_from_array',
            'options' => $this->subcategories(),
            'allows_null' => false,
        ];

        array_unshift($this->crud['fields'], $parentField1,$parentField);

    }

public function categories()
{
    $cat = Request::get('cat_id');

    $currentId = 0;
    if (Request::segment(4) == 'edit' and is_numeric(Request::segment(3))) {
        $currentId = Request::segment(3);
    }

    $entries = Category::where('translation_lang', config('app.locale'))->where('parent_id',0)->orderBy('lft')->get();
    if (is_null($entries)) {
        return [];
    }

    $tab = [];
    $tab[0] = 'Root';
    foreach ($entries as $entry) {
        if ($entry->id != $currentId) {
            $tab[$entry->translation_of] = '- ' . $entry->name;
        }
    }
    return $tab;
}

public function subcategories()
{
    $currentId = 0;

    if (Request::segment(4) == 'edit' and is_numeric(Request::segment(3))) {
        $currentId = Request::segment(3);
    }

    $entries = Category::where('translation_lang', config('app.locale'))->where('parent_id','!=' ,0)->orderBy('lft')->get();

    if (is_null($entries)) {
        return [];
    }

    $tab = [];
    $tab[0] = 'Root';
    foreach ($entries as $entry) {
        if ($entry->id != $currentId) {
            $tab[$entry->translation_of] = '- ' . $entry->name;
        }
    }
    return $tab;
}

我想要subcategories() 中所选选项的 id,我可以使用该 id 来获取数据。

【问题讨论】:

  • 您在 __construct 方法上缺少结束 }

标签: php laravel-5.2 laravel-backpack


【解决方案1】:

我认为对您来说最好的方法是为此特定目的创建一个自定义字段类型,包括两个选择。关注this procedure。从select2.blade.php 文件开始,添加实现目标所需的javascript(在第一个select2 上的更改事件中,在下一个select2 中更改选项)。

【讨论】:

  • 实际上,在我的数据库中,类别和子类别都保存在同一个表中,我不知道如何编写关系。当我使用 select2 时,他们要求使用关系函数.....请帮我解决这个问题
  • 我明白了。没有关系,select2 字段将无法工作。老实说,关系在 Laravel 中是必须要做的。否则你可能根本不应该使用 Laravel。您可以在此处的文档中了解关系:laravel.com/docs/5.3/eloquent-relationships - 但我个人建议在 Laracasts 每月花费 9 美元。通过观看一些视频,您可以非常轻松地学习 Laravel。这个特别解释了很多核心概念,以及关系(视频 8):laracasts.com/series/laravel-5-from-scratch
猜你喜欢
  • 2017-05-10
  • 1970-01-01
  • 1970-01-01
  • 2017-02-18
  • 2017-03-27
  • 1970-01-01
  • 2016-11-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多