• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
2 column table to form_dropdown array

#1
[eluser]chris...[/eluser]
I have a simple 2 column table

Code:
ID name
1  Bay-1
2  Bay-2
3  Admin
etc

Id like to enter this into an array for use in form_dropdown() so i get this result

Code:
<option value="1">Bay-1</option>
<option value="2">Bay-2</option>
<option value="2">Admin</option>

Is there a simplified way to do this?

#2
[eluser]malzahar[/eluser]
Something like this may work.

In your model:
Code:
function get_names() {
   $names= array();
   $query = $this->db->get('table_name');
   if($query->num_rows() > 0) {
      foreach($query->result_array() as $name) {
         $names[] = $name;
      }
   }
   $query->free_result();
   return $names;
}

Your controller:
Code:
$this->load->model('model_name');
$data['names'] = $this->Model_Name->get_names();
$this->load->view('view_name', $data);

Your view:
Code:
foreach($names as $name) {
   echo "<option value='{$name['id']}'>{$name['name'}</option>";
}

#3
[eluser]chris...[/eluser]
Not what I had in mind, I do the same thing a bit differently in order to keep the view clean and use the helper form_dropdown() main difference is my model contains this

Code:
$names[$name['id']] = $name['name'];

#4
[eluser]malzahar[/eluser]
In that case once you create the $names array in the model and pass it to the view you can just load it into the form helper.

Code:
echo form_dropdown('dropdown_name', $names, 'selected_value');

#5
[eluser]malzahar[/eluser]
deleted comment

Nevermind that should amount to the same thing had a brain fart there.

#6
[eluser]chris...[/eluser]
its a 'key' => 'value' array

#7
[eluser]malzahar[/eluser]
Once you have that associative array though you should be able to just pass it to the form_dropdown() function as described above.

#8
[eluser]chris...[/eluser]
yeah was just wonder if there was an easy way to just get the data from the database in that format
where can i read up on how many-to-one relational tables are done in codeignighter
or do I code them manually with sql commands?

#9
[eluser]CroNiX[/eluser]
Nope, even using straight php/mysql you have to loop over it to get it in that format.

I just create a helper, array_to_dropdown($array, $key_field, $value_field, $default_value), where I can pass it the database result array (or any array), the field I want to use for the 'id' index, the key for the 'text' part, and an optional default first value, and it loops over the array creating the new desired array and returning it.

#10
[eluser]chris...[/eluser]
no problem, all done, made my own function


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.