我正在尝试为类别创建一个下拉列表。如果这检查没问题,那么它必须是数据库。
型号:
分类 var $hasMany = 'Product';
产品 var $belongsTo = 'Category';
ProductsController 添加功能:
$this->loadModel('Category');
$this->set('Categories',$this->Category->find('list',array('order'=> array('Category.name'))));
$this->set(compact('Categories'));
最佳答案
Nebojsac 是正确的,因为您在 View 中两次设置变量“$Categories”。事实上,$this->set(compact('Categories'));
实际上可能会用空值覆盖对 set() 的第一次调用。您应该使用:
$this->set('categories', $this->Category->find('list'));
或者:
$categories = $this->Category->find('list');
$this->set(compact('categories'));
当您使用 compact 时,它会查找名为 $categories 的变量,然后将该变量设置为 $categories 以便在 View 中访问。
为了您的
category_id
( 或任何外键是 )字段要自动填充类别,您应该确保使用带有 Product
的表单创建表单。模型:echo $this->Form->create('Product');
此外,表单输入应该是:
echo $this->Form->input('category_id');
如果您想手动指定下拉菜单的选项,您可以再次使用
$this->set('categories', $this->Category->find('list'));
将类别传递给 View 。 .然后在您的 View 文件中,设置
options
数组键等于 $categories:echo $this->Form->input('category_id', array('type' => 'select', 'options' => $categories));
关于CakePHP:下拉列表(外键),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11592498/