0

codeIgniter form_dropdown() function can receive only associative array but I have multi dimension array by using result_array() function. How can I fetch my data on form_dropdown() function?

0

2 Answers 2

1

Let's say you want a dropdown of items, using result_array():

$query = $this->db->query("SELECT id, item_name FROM items");

$options = array();

foreach ($query->result_array() as $row){
   $options[$row['id']] = $row['item_name'];
}

echo form_dropdown('my_items_dropdown', $options, '1');
Sign up to request clarification or add additional context in comments.

3 Comments

But my query is not stay in model. If I want to separate logic and presentation. how can I build model function and how can I show my view page
check out Jamie rumbelows my_model class, it has a method for getting an associative array from a table.
I think the idea is that you generate and return the $options in your model. So the above code would reside in your model with: return $options. Then in your controller you can then do something like: $data['item_options'] = $this->load->model('items_model'); Then in your controller also pass this to your view: $this->load->view('my-view', $data); Then in your view: <?= form_dropdown('my_items_dropdown',$item_options,'1'); ?>
0

I have extended the class DB_result.php in system/database with this new function

public function dropdown_array($id_field = FALSE, $list_field = FALSE) 
{
    $result = array();

    if ($id_field === FALSE || $list_field === FALSE) return $result;

    $array = $this->result_array();

    foreach ($array as $value) {
        $result[$value[$id_field]] = $value[$list_field]; 
    }
    return $result;
}

Now you can simply call from every Model class your new function to generate a dropdown-compliant array like this:

    $customers = $this->db->get('customers');
    $result = $customers->dropdown_array('id', 'name');
    return $result;

Comments