简体   繁体   中英

Question about form_dropdown with Codeigniter

I have a question about using form_dropdown() .

The code below works, but i am unsure about if I have to do the new array in the view or is there a better way of doing it with the array $games - passed from $data['games'] ?

Should I be doing all the processing in the controller and sending over a ready array to populate the dropdown?

I tried this in the view: echo form_dropdown('games', $games); but got the error "Object of class stdClass could not be converted to string", I think it's because its an array of objects and I have to convert it?

TABLE: GAMES

GM_ID - int

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();
  }
}

CONTROLLER

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();

You are correct that it needs to be converted from an object to an array, the keys are your input values, and the array values are the text displayed in the <option> when you use form_dropdown() . The way you are doing it is fine, and I personally recommend it.

Reason: The form controls and HTML/text output are view logic. For instance, what if you want to do this instead?:

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

That's just my perspective, it really doesn't matter too much, but usually as a rule - HTML and presentation logic should be in the view.

Aside : your function name get_game_names() is confusing because it returns more than just names. Also for simplicity's sake, you're using ActiveRecord so you can just do this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM