2011-07-22 93 views
2

我對使用form_dropdown()有疑問。關於使用Codeigniter的form_dropdown的問題

以下作品的代碼,但我不確定我是否要做新的數組中的視圖或有與陣列$games做一個更好的方式 - 從$data['games']通過呢?

我應該在控制器中完成所有的處理,並通過一個準備好的數組來發送下拉菜單嗎?

我在視圖中試過這個:echo form_dropdown('games', $games);,但得到了錯誤「類stdClass的對象無法轉換爲字符串」,我認爲這是因爲它的對象數組,我必須將其轉換?

表:遊戲

GM_ID - 詮釋

GM_NAME - VAR

MODEL:

class Test_model extends CI_Model { 

    function __construct() 
    { 
    // Call the Model constructor 
    parent::__construct(); 
    } 
    function get_game_names() 
    { 
    $queryg = $this->db->query("SELECT * FROM games"); 
    return $queryg->result(); 
    } 
} 

控制器

class Test extends CI_Controller { 

    public function index() 
    { 
    $this->load->model('test_model'); 
    $data['games'] = $this->test_model->get_game_names(); 
    $this->load->view('view_test',$data); 
    } 

} 

VIEW

$this->load->helper('form'); 
echo form_open('send'); 

$list = array(); //is this the best way to do it?? 
foreach($games as $row) 
{ 
    $list[$row->GM_ID] = $row->GM_NAME; //is this the best way to do it?? 
} 

echo form_dropdown('games', $list); //then pass this array? 
echo form_close(); 

回答

1

你是正確的,它需要從一個對象轉換爲一個數組,鍵是你的輸入值,而數組的值是在<option>顯示的文本當你使用form_dropdown()。你這樣做的方式很好,我個人推薦它。

原因:窗體控件和HTML /文本輸出是視圖邏輯。舉例來說,如果你想這樣做,而不是?:

$list[''] = 'Please select a game'; 
foreach($games as $row) 
{ 
    $list[$row->GM_ID] = ucfirst(htmlspecialchars($row->GM_NAME)); 
} 

這只是我的觀點是什麼,它確實沒有太大的關係,但通常作爲一項規則 - HTML和表示邏輯應該是在視圖中。

Aside:您的函數名稱get_game_names()令人困惑,因爲它返回的不僅僅是名稱。同樣爲了簡單起見,您使用的是ActiveRecord,因此您可以這樣做:

function get_games() 
{ 
    return $this->db->get('games')->result(); 
}