4

我正在尝试为类别创建一个下拉列表。如果这检查没问题,那么它必须是数据库。

楷模:

类别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'));  
4

2 回答 2

5

Nebojsac 是正确的,因为您在视图中设置了两次变量“$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 以便在视图中访问。

为了使您的category_id或任何您的外键)字段自动填充类别,您应该确保使用带有Product模型的表单创建表单:

echo $this->Form->create('Product');

此外,表单输入应为:

echo $this->Form->input('category_id');

如果您想手动指定下拉菜单的选项,您可以再次使用 . 将类别传递给视图$this->set('categories', $this->Category->find('list'));

然后在您的视图文件中,将options数组键设置为等于 $categories:

echo $this->Form->input('category_id', array('type' => 'select', 'options' => $categories));
于 2012-07-23T01:08:22.130 回答
3

我希望你有与 belongsTO 类别表相关联的产品模型表。您想在我的下拉列表中显示类别的数据。

$Categories= $this->Product->Category->find('list'); $this->set(compact('Categories'));

并在您的 ctp 页面中执行此操作

echo $this->Form->input('category_id');

于 2015-09-24T12:06:25.313 回答