Kees Sonnema
Kees Sonnema

Reputation: 5784

$selected attribute not working in codeigniters form_dropdown()

I have an editform with a dropdown for choosing a category. I also made a function for getting the category from the database.

I set an array $opties for the dropdown to select form and a 'selected' parameter called $selectie this one contains the category for that specific company in the database.

It looks like this:

<tr>
<td><?= form_label('Categorieen'); ?></td>
<td><?= form_dropdown('categorieen', $opties, $selectie); ?></td>
</tr>

Question

Why is my 'selected' part not working?

When I do a print_r($selectie) I get:

Array
(
    [12] => Vlaggen
)

which is my category in the database.

When I do a print_r($opties) I get:

Array
(
    [11] => Webdesign
    [12] => Vlaggen
    [13] => Auto-s
    [14] => Electronica
    [15] => Boeken
    [16] => Antiek-en-Kunst
    [17] => Auto-Onderdelen
    [18] => Computers-Hardware
    [19] => Computers-Software
)

I don't know what the problem is. Some help would be appreciated.

Controller:

function updatebedrijven()
{
    $dbres = $this->db->get('categorieen');
    $ddmenu = array();
    foreach ($dbres->result_array() as $tablerow) {
        $ddmenu[$tablerow['idcategorieen']] = $tablerow['Categorie'];
    }
    $data['opties'] = $ddmenu;
    $id = $this->uri->segment(3); 
    $id2 = $this->uri->segment(3); 

    $data['selected'] = $this->members_model->getselection($id2);

    $data['info'] = $this->members_model->getbedrijf($id); 
    $data['id'] = $id;
    $this->load->view('members/header');
    $this->load->view('members/editform', $data);
    $this->load->view('members/footer');    
}

Model:

//This one is for the $opties

function getbedrijf($id) 
{ 
    $this->db->where('idbedrijven', $id); 
    $query = $this->db->get('bedrijven'); 

    if ($query->num_rows() == 1) { 
    $row = $query->row_array(0); 

    return $row; 
    } 
}

//This one is for the $selectie

function getselection($id2)
{
    $this->db->from('bedrijfcategorieen');
    $this->db->join('categorieen', 'bedrijfcategorieen.idcategorieen = categorieen.idcategorieen');
    $this->db->where('bedrijfcategorieen.idbedrijven', $id2);
    $query = $this->db->get();

    return $query->result();
}

Upvotes: 0

Views: 403

Answers (1)

tomexsans
tomexsans

Reputation: 4527

form_dropdown uses the arrays key => value as its 'value' and 'option', to select a data from your dropdown you will need the key of your selected data for example you choose

[12] => Vlaggen to select it you need its key which is 12, and not an array like

Array
(
    [12] => Vlaggen
)

<? 
//just for testing
echo form_dropdown('categorieen', $opties, key($selectie)); 
?>

Upvotes: 2

Related Questions