在控制器中:
public function add() {
if ($this->data) {
if ($this->Item->save($this->data)) {
$this->redirect(…);
}
}
$categories = $this->Item->Category->find('list');
$this->set(compact('categories'));
}
观点:
echo $this->Form->input('category_id');
(相当于:)
echo $this->Form->input('category_id', array('type' => 'select', 'options' => $categories));
您只需要获取find('list') 专门用于的类别列表,以及
允许用户选择类别的输入元素。 category_id 将像 Item 模型的任何其他字段一样保存。
如果您想从其他页面预填充类别,请使用以下内容:
public function add($category_id) {
$category = $this->Item->Category->find('first', array('conditions' => array('Category.id' => $category_id), 'recursive' => -1));
if (!$category) {
$this->Session->setFlash('Select a valid category');
$this->redirect(array('controller' => 'categories', 'action' => 'select_category'));
}
if ($this->data) {
$this->data['Item']['category_id'] = $category_id;
if ($this->Item->save($this->data)) {
$this->redirect(…);
}
}
$this->set(compact('category'));
}
查看:
<p>Adding item to category <?php echo $category['Category']['name']; ?></p>
<?php echo $this->Form->create('Item', array('url' => array('action' => 'add', $category['Category']['id']))); ?>
从您的类别选择列表中,只需链接到项目添加操作:
echo $this->Html->link("Add item to {$category['Category']['name']}", array('controller' => 'item', 'action' => 'add', $category['Category']['id']));