2016-09-23 68 views
0

我在我的新項目中使用Laravel 5.2揹包,其中我的表單中有一個select_from_array字段,具體取決於我希望數據在另一個select_from_array字段中顯示的選定值。不知道該怎麼做。請幫我解決一下這個。這是我的代碼使用laravel從select_from_array字段獲取選定值5.2揹包

Controller.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來獲取數據。

+0

您錯過了__construct方法的結束'}'。 –

回答

0

我認爲你最好的辦法是爲這個特定目的創建一個自定義字段類型,其中包括兩個選擇。按照this procedure。從select2.blade.php文件開始,添加實現目標所需的JavaScript(在第一個select2上的更改事件中,更改下一個select2中的選項)。

+0

實際上,在我的數據庫中,類別和子類別都保存在同一張表中,我不知道如何寫關係。當我使用select2他們要求關係功能.....請幫我這個 –

+0

我明白。如果沒有關係,select2字段將不起作用。老實說,關係是Laravel必須做的。否則,你可能根本不應該使用Laravel。您可以在這裏的文檔中瞭解關係:https://laravel.com/docs/5.3/eloquent-relationships - 但我個人建議花費9美元一個月的時間訪問Laracasts。通過觀看一些視頻,您可以非常輕鬆地學習Laravel。這個特別解釋了很多核心概念以及關係(視頻8):https://laracasts.com/series/laravel-5-from-scratch – tabacitu