Reputation: 569
I am trying to create a drop down list for categories. If this checks out to be okay than it must be the database.
Models:
Category var $hasMany = 'Product';
Product var $belongsTo = 'Category';
ProductsController add function:
$this->loadModel('Category');
$this->set('Categories',$this->Category->find('list',array('order'=> array('Category.name'))));
$this->set(compact('Categories'));
Upvotes: 4
Views: 3687
Reputation: 465
I hope you have Product model table associated with belongsTO Category Table. you want to display the Category' data to my dropdown list.
$Categories= $this->Product->Category->find('list'); $this->set(compact('Categories'));
and in your ctp page do it this
echo $this->Form->input('category_id');
Upvotes: 3
Reputation: 1194
Nebojsac is correct in that you are setting the variable "$Categories" twice in the view. In fact, $this->set(compact('Categories'));
may actually be overwriting the first call to set() with a blank value. You should either use:
$this->set('categories', $this->Category->find('list'));
OR:
$categories = $this->Category->find('list');
$this->set(compact('categories'));
When you use compact, it is looking for a variable named $categories, and it then sets that variable to $categories to be accessible in the view.
In order for your category_id
(or whatever your foreign key is) field to be automatically populated with the categories, you should make sure that you are creating the form using the form with the Product
model:
echo $this->Form->create('Product');
Also, the form input should be:
echo $this->Form->input('category_id');
If you want to specify the options for your drop down manually, you can once again pass the categories to the view using $this->set('categories', $this->Category->find('list'));
.
Then in your view file, set the options
array key equal to $categories:
echo $this->Form->input('category_id', array('type' => 'select', 'options' => $categories));
Upvotes: 5