user1978081
user1978081

Reputation:

How can I use CodeIgniter form dropdown function?

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?

Upvotes: 0

Views: 784

Answers (2)

XcodeJunkie
XcodeJunkie

Reputation: 424

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;

Upvotes: 0

prograhammer
prograhammer

Reputation: 20590

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

Upvotes: 1

Related Questions