Just solved one issue here, now another...
As mentioned before, I'm following this tutorial to create a simple shopping cart using CakePHP, Ajax and Bootstrap.
I've got it working for the most part except it appears though that the items added to the cart aren't saved. I can add an item, move around the website and even change it's quantity and it remains as is - however, when I try to add another item - the second item just completely overwrites the first item.
This is the CakePHP Cart Model function that runs when adding an item:
public function addProduct($productId) {
$allProducts = $this->read();
if (null!=$allProducts) {
if (array_key_exists($productId, $allProducts)) {
$allProducts[$productId]++;
} else {
$allProducts[$productId] = 1;
}
} else {
$allProducts[$productId] = 1;
}
$this->saveProduct($allProducts);
}
public function saveProduct($data) {
return CakeSession::write('cart',$data);
}
That's called by the add
Function in the Controller:
public function add() {
$this->autoRender = false;
if ($this->request->is('post')) {
$this->Cart->addProduct($this->request->data['Cart']['product_id']);
}
echo $this->Cart->getCount();
}
My Cart Model looks like this at the start:
<?php
App::uses('AppModel', 'Model');
App::uses('CakeSession', 'Model/Datasource');
class Cart extends AppModel {....}
$this->read()
? – RossCakeSession
instead of Session Component? – Nunser$this->read()
- when you call it you'll get the data for one item returned. You then overwrite the session data with that one item's data. @Nunser there's no session component in a model; there is a static session interface anywhere though. – AD7sixpublic function readProduct() {return CakeSession::read('cart');}
– Chronix3