CakePHP: Get category ID from Categories table and insert to a column in Items table
I'm new to CakePHP and I trying out some of the tutorials on it.
Currently I have a Categories table and an Items table; Category hasMany Item and Item belongsTo a Category.
On my Items table, I have a category_id column that refers to a category ID in the Categories table.
A user is only limited to adding an item t开发者_如何学Pythonhrough the categories view.ctp page and it'll redirect user to the items add.ctp page. The add() function resides in the items controller.
How do I get the ID of the category which the user wish to add an item to and insert them to category_id column whenever a user adds an item?
Thanks in advance.
In the controller:
public function add() {
if ($this->data) {
if ($this->Item->save($this->data)) {
$this->redirect(…);
}
}
$categories = $this->Item->Category->find('list');
$this->set(compact('categories'));
}
The view:
echo $this->Form->input('category_id');
(which is equivalent to:)
echo $this->Form->input('category_id', array('type' => 'select', 'options' => $categories));
You just need to get a list of categories, which find('list')
is specialized for, and an
input element which lets the user select a category. The category_id
will be saved like any other field of the Item
model.
If you want to prefill the category from a different page, use something like this:
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'));
}
View:
<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']))); ?>
From your category selection list, just link to the Item add action:
echo $this->Html->link("Add item to {$category['Category']['name']}", array('controller' => 'item', 'action' => 'add', $category['Category']['id']));
精彩评论