Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CodeIgniter - Adding a default value to a form_dropdown

I'm wondering if someone can help me out. I have a form_dropdown which I'm filling with options from the database. I want to add a default "Please Select" value at the top of the list, but can't figure out how to do it without adding that to the database.

My code is as follows:

function populatedropdown()
{
    $query = $this->db->query('SELECT * FROM '.$this->table_name.' WHERE active=1 ORDER BY brand');
    $dropdowns = $query->result();

    foreach($dropdowns as $dropdown) {
        $dropDownList[$dropdown->brand] = $dropdown->brand;
    }
    $finalDropDown = $dropDownList;

    return $finalDropDown;
}
like image 428
BigJobbies Avatar asked Jan 16 '12 21:01

BigJobbies


2 Answers

Another way to write it would be:

function populatedropdown()
{
    $query = $this->db->query('SELECT * FROM '.$this->table_name.' WHERE active=1 ORDER BY brand');

    if ($query->num_rows() > 0) {
        $dropdowns = $query->result();

        $dropDownList[''] = 'Please Select';    // default selection item
        foreach($dropdowns as $dropdown) {
            $dropDownList[$dropdown->brand] = $dropdown->brand;
        }

        return $dropDownList;
    } else {
        return false;       // return false if no items for dropdown
    }
}
like image 54
Jakub Avatar answered Oct 22 '22 06:10

Jakub


Just add it to the array before you return it.

function populatedropdown()
{
    $query = $this->db->query('SELECT * FROM '.$this->table_name.' WHERE active=1 ORDER BY brand');
    $dropdowns = $query->result();

    foreach($dropdowns as $dropdown) {
        $dropDownList[$dropdown->brand] = $dropdown->brand;
    }
    $finalDropDown = array_merge(array('' => 'Please Select'), $dropDownList);

    return $finalDropDown;
}
like image 7
Rocket Hazmat Avatar answered Oct 22 '22 07:10

Rocket Hazmat