在控制器:
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')
是專門爲和一個 輸入元素,讓用戶選擇一個ca tegory。 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']));
Hi deceze,I sea圍繞着CakePHP的框架,併爲它提供了更長的解決方案。在類別view.ctp中,我創建了一個添加鏈接,用於在類別控制器中執行「重定向」功能。在重定向函數中,我使用帶條件的find()方法來查找與名稱對應的ID。該對象被放置到會話中,然後將用戶重定向到餐館控制器。這樣用戶不必從下拉列表中選擇,而是點擊類別頁面來添加項目。感謝您的意見。祝你有美好的一天。 – fred1234 2011-05-22 09:54:44
@fred在這種情況下,看看我的更新。 – deceze 2011-05-22 11:11:22