David Pride David Pride - 2 years ago 161
PHP Question

CodeIgniter - dropdown menu passing position in list to db rather than value

I'm writing a small app using Codeigniter and run into a few issues so far! I have a drop down list that is populated from a db table. The drop down is populated and displays correctly however when I try to save its contents (values) to a new db table, it is saving the position in the dropdown list, rather than the value that is displayed.

Part of the form in View:

<?php echo form_open('manage/create_sold_vehicle_record'); ?>
Registration Number
<?php echo form_dropdown('reg_no', $vehicle_list, 'large'); ?>

The relevant part of the controller:

function sell_vehicle()

$id = $this->uri->segment(3);
$vehicles_qry = $this->MVehicle->listSaleVehicles();

$vehicle_list = array();
foreach ($vehicles_qry->result() as $vehicle)
$vehicle_list[] = $vehicle->reg_no;

$data['vehicle_list'] = $vehicle_list;
$data['main_content'] = 'sell_stock_vehicle';
$this->load->view('includes/template', $data);

This is the Model:

function create_sold_vehicle_record()

$new_vehicle_insert_data = array(
'reg_no' => $this->input->post('reg_no'), <-- This is saved to db, but is the position in dropdown list, not the value shown.
'sold_by' => $this->input->post('staff'),
'bought_by' => $this->input->post('customer'),
'sale_price' => $this->input->post('sale_price'),
'comm_rate' => $this->input->post('comm_rate'),
'total_comm' => $this->input->post('total_comm'),
'sale_date' => $this->input->post('date')

$insert = $this->db->insert('sold_vehicles', $new_vehicle_insert_data);

return $insert;

So, rather than for example save 'OU03XHC' as the reg_no value in db, it is saving '1' (or whatever the position of the value was in the drop down list).

Answer Source

$vehicle_list[] needs to be an associative array

$vehicle_list = array();
foreach ($vehicles_qry->result() as $vehicle)
    $vehicle_list[$vehicle->reg_no] = $vehicle->reg_no;

Now form_dropdown() produces also option values (other than 0,1,etc.) in the dropdown html

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download