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'));
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With