2014-02-20 14 views
0

我想在Laravel中創建一個下拉列表,其中的選擇選項是來自我的數據庫的值,並且存在一些問題。在本網站的其他教程中,下拉列表查詢爲您的數據庫建立模型。我還沒有創建模型類,我不打算。在Laravel中建立下拉列表(無模型)

routes.php文件

Route::get("/user/charname", array(
    'as' => 'profile-character', 
    'uses' => '[email protected]' 
)); 

ProfileController.php

class ProfileController extends BaseController 
{ 
    public function dropDownList() 
    { 
     $list = DB::table('characters')->where('char_id', '128')->pluck('char_name'); 
     return View::make('layout.profile')->with('character_options',$list); 
    } 
} 

在profile.blade.php(視圖)

<div class="selected_char"> 
    <form action="{{ URL::route('profile-character') }}" method="post"> 
     <li> 
      {{ Form::select('character_options', $list ,Input::old('character_options')) }} 
     </li> 
    </form> 
</div> 

通過這樣做,它說,從$列表我的觀點是未定義的。我在哪裏在視圖定義$列表,我如何落實從我的控制器,以查看$列表中,因爲這一行似乎並沒有做的工作

return View::make('layout.profile')->with('character_options',$list); 

回答

1

你需要在視圖中使用$character_options$list

+0

我已經完成了必要的修改在我的代碼{{表::選擇( 'character_options',$ character_options,輸入::老( 'character_options'))}}。你說的很有道理,但我不明白它爲什麼仍然不起作用。它現在說character_options是profile.blade.php中的未定義變量 –

1

您實際上指定在View::make()調用中該變量應該是'character_options',因此您需要將其稱爲$character_options

此外,->lists('char_name')比使用->pluck('char_name')更好,因爲它會給你完整的清單。 Pluck只是返回找到的第一個項目。

除此之外,使用->lists('char_name', 'id')可以獲取id列的鍵值列表,如果您要使用此列表來確定外鍵字段的ID,這將非常有用。但如果沒有的話,不要大。

+0

在我的視圖中{{Form :: select('character_options',$ character_options,Input :: old('character_options'))}} –

+0

對我來說這聽起來很合理,但從你的其他評論看起來並不適合你。如果實際上粘貼了控制器或視圖代碼的簡化版本,則可以嘗試提供更多細節 - 可能會干擾可用變量,但由於您爲簡潔起見刪除了一些代碼,因此我們無法看到它。也許你可以將控制器和視圖簡化爲最簡單的形式,然後按照自己的方式工作 - 通常會看到導致大問題的一個小問題。 – alexrussell

0

我已經部分地被我認爲這樣做解決了問題:

{{ Form::select('list', DB::table('characters')->where('char_id', '128')->lists('char_name') ,Input::old('list')) }} 

我個人不認爲這是一個可行的解決方案,而是一個臨時

{{表::選擇( 'character_options',$ character_options,輸入::老( 'character_options'))}}

錯誤:未定義的變量character_options

{{表::選擇('character_opt離子',$列表,輸入::舊('character_options'))}} 錯誤:未定義的變量列表

也許我不明白我是如何將變量從控制器發送到視圖。

0

您需要使用lists,如@alexrussel所述。請注意,View::make('layout.profile')->with('character_options',$list);,在這裏您傳遞的變量爲$character_options,其中包含的值$list$list將不再可用於視圖。

ProfileController.php

<?php 

class ProfileController extends BaseController 
{ 
    public function dropDownList() 
    { 
     $list = DB::table('characters')->where('char_id', '128')->lists('char_name'); 
     return View::make('layout.profile')->with('character_options',$list); 
    } 
} 

profile.blade。PHP

<div class="selected_char"> 
<form action="{{ URL::route('profile-character') }}" method="post"> 
    <li> 
     {{ Form::select('character_options', $character_options ,Input::old('character_options')) }} 
    </li> 
</form>