Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code Igniter - form_dropdown selecting correct value from the database

Tags:

codeigniter

Im having a few problems with the form_dropdown function in CodeIgniter .... My application is in 2 parts, a user goes in, enters a form and submits it .... once its submitted a admin can go in and edit that persons form and then save it to database.

So, to display the dropdown in the initial form, im using the following ( all the options in the dropdown are coming from the database )

Model:

    function get_salaries_dropdown()
{
    $this->db->from($this->table_name);
    $this->db->order_by('id');
    $result = $this->db->get();
    $return = array();
    if($result->num_rows() > 0){
            $return[''] = 'please select';
        foreach($result->result_array() as $row){
            $return[$row['id']] = $row['salaryrange'];
        }
    }
    return $return;
}

Then in the Controller:

$data['salaries'] = $this->salary_expectation->get_salaries_dropdown();

Then finally the View:

<?php echo form_dropdown('salaries', $salaries, set_value('salaries', $salaries));  ?>

That bit works perfect in displaying the dropdown filled with values for the user to select.

So, when the user selects a value, then hits save, its saved to the database.

On the Edit page which the admin see's, im using the same code to display the dropdown filled with options, but how do i get it to automatically choose the one thats been selected by the user in the initial stage?

Cheers,

like image 775
Chris Avatar asked Oct 14 '22 20:10

Chris


1 Answers

According to Codeigniter documentation

The first parameter will contain the name of the field, the second parameter will contain an associative array of options, and the third parameter will contain the value you wish to be selected. You can also pass an array of multiple items through the third parameter, and CodeIgniter will create a multiple select for you.

Your admin controller should have something like

$data['selected'] = $this->salary_expectation->get_salary_selected();

According to this, the admin view should be like this

<?php echo form_dropdown('salaries', $salaries, $selected_value);  ?>
like image 131
vikmalhotra Avatar answered Oct 17 '22 23:10

vikmalhotra