Reputation: 31
Apologies for my nebie like question but i'm trying to learn a lot here, new to MVC and CodeIgniter.
I have a simple CRUD that i'm building, but i'm stumped on what I think is a very simple thing if you know what you are doing.
I have a View that is being used to Update a Tyre to the db into a table 'tyres'. In that View I want to display a dropdown of Brands that are held in a seperate db table 'brands'. In my Model I have a class of Tyres and in that I have a function :
public function get_tyres($id = FALSE)
{
if ($id === FALSE)
{
$query = $this->db->get('tyres');
return $query->result_array();
}
$query = $this->db->get_where('tyres', array('id' => $id));
return $query->row_array();
}
This allows me to access the Tyres data in my Controller and send the data through to the View using :
$data['tyres_item'] = $this->tyres_model->get_tyres($id);
$this->load->view('tyres/update', $data);
In my View I access the $data['tyres_item'] so that I can prefill the form with db data.
BUT
How do I access the Brands data from the db to build a dropdown list of all Brands in my view? I have separate Model and Controller for Brands but I can't access them in the View.
I tried adding
$data['brands'] = $this->brands_model->get_brands();
to my update function in my Tyre Controller but i understand that this won;t work because I am inside the Tyres Controller and not the Brands Controller.
How can I accomplish this, I know I must be missing something straightforward...
Here's my View : and what I want to accomplish :
echo form_open('tyres/update');
?>
<label for="tyre">Tyre</label>
<input type="input" name="tyre" value="<?=$tyres_item['tyre']?>" />
<label for="brand">Brand</label>
<?php
echo form_dropdown('brands', $data['brands']);
?>
...
EDIT- I've added the brands model to the construct and that has helped, I can now access the brands data in my view using :
echo form_dropdown('brands', $brands);
But it returns an array so I added the following :
echo form_dropdown('brands', $brands['brand']);
This then errors out with :
Message: Undefined index: brand
I'm stuck AGAIN! Help.
Upvotes: 1
Views: 55
Reputation: 31
Got It!
I needed to loop through the db result then add that to the form_dropdown :
foreach($brands as $brand)
{
$brand_list[$brand['id']] = ucfirst(htmlspecialchars($brand['brand']));
}
echo form_dropdown('brands', $brand_list, $tyres_item['brand']);
This might help someone.
Upvotes: 1